DEV Community

Mac
Mac

Posted on

Spring Boot : Handling Exception

Example of how to handling exception in Spring Boot.

  • Annotate Exception with @ResponseStatus
@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR, reason = "I don't know...")
public class MyException extends Exception {

    public MyException(String message) {
        super(message);
    }
}

This will response HTML error page as screenshot below.

  • Throw ResponseStatusException from Controller.
@GetMapping("/users/{id}")
public User findUser(@PathVariable Long id) throws MyException {
    throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "I don't know this too...");
}
  • Use @ControllerAdvice as global exception handling.
@ExceptionHandler(MyException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public String handleMyException(HttpServletRequest request, Throwable ex) {
    return "I don't know anything...";
}

We can remove @ResponseBody if we use @RestControllerAdvice instead of @ControllerAdvice

Top comments (0)