Suppose there is a REST UserController
managing /user
resource:
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public List<User> listUsers() {
return userService.listUsers();
}
@GetMapping("/users/{id}")
public User getUser(@PathVariable long id) {
return userService.getUser(id);
}
@PostMapping("/users")
public ResponseEntity<?> createUser(User user) {
User user = userService.createUser(user);
URI location = URI.create("/users/" + user.getId());
return ResponseEntity.created(location).build();
}
@PutMapping("/users/{id}")
public ResponseEntity<?> updateUser(@PathVariable long id, User user) {
userService.updateUser(id, user);
return ResponseEntity.noContent().build();
}
@DeleteMapping("/users/{id}")
public ResponseEntity<?> deleteUser(@PathVariable long id) {
userService.deleteUser(id);
return ResponseEntity.noContent().build();
}
}
We can see that the controller passes user identifier to the user
service in three methods. Apparently, there may be a situation when
there is no user with such id. In this case UserNotFoundException
is
thrown.
How would you change the code to return 404 in that case?
Follow-up:
- What if we want to return 404 if this exception is thrown for any request not only in this controller?