Skip to content

Instantly share code, notes, and snippets.

@dantonyuk
Last active July 15, 2020 17:43
Show Gist options
  • Save dantonyuk/46a1c1fe49a966406d84e3f3fc2b5cc9 to your computer and use it in GitHub Desktop.
Save dantonyuk/46a1c1fe49a966406d84e3f3fc2b5cc9 to your computer and use it in GitHub Desktop.

Exception Handling in Spring MVC

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?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment