http stauts code handling
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user