http stauts code handling

This commit is contained in:
haerong22
2020-11-26 18:39:53 +09:00
parent 2df8b99bfb
commit 74ee92c8ec
2 changed files with 32 additions and 2 deletions

View File

@@ -1,7 +1,10 @@
package com.example.restfulwebservice.user;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.List;
@RestController
@@ -19,12 +22,24 @@ public class UserController {
@GetMapping("/users/{id}")
public User retrieveUser(@PathVariable int id) {
return userDaoService.findOne(id);
User user = userDaoService.findOne(id);
if (user == null) {
throw new UserNotFoundException(String.format("ID[%s] not found", id));
}
return user;
}
@PostMapping("/users")
public void createUser(@RequestBody User user) {
public ResponseEntity<User> createUser(@RequestBody User user) {
User savedUser = userDaoService.save(user);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedUser.getId())
.toUri();
return ResponseEntity.created(location).build();
}
}

View File

@@ -0,0 +1,15 @@
package com.example.restfulwebservice.user;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
// HTTP Status code
// 2XX -> OK
// 4XX -> Client error
// 5XX -> Server error
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}