Defining custom exception handling advice for TodoNotFoundException

When TodoNotFoundException occurs anywhere in the application, we want to return a response adhering to the structure of ExceptionResponse.

We can do that by creating a controller advice extending the default exception handling mechanism in Spring Boot. The following code shows the details for handling TodoNotFoundException.class:

@ControllerAdvice
@RestController
public class RestResponseEntityExceptionHandler
extends ResponseEntityExceptionHandler {

@ExceptionHandler(TodoNotFoundException.class)
public final ResponseEntity<ExceptionResponse>
todoNotFound(TodoNotFoundException ex) {

ExceptionResponse exceptionResponse =
new ExceptionResponse( ex.getMessage(),
"Any details you would want to add");

return new ResponseEntity<ExceptionResponse>
(exceptionResponse, new HttpHeaders(),
HttpStatus.NOT_FOUND);

}

}

Some important things to note are as follows:

  • RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler: We are extending ResponseEntityExceptionHandler, which is the base class provided by Spring MVC for centralized exception handling when it comes to ControllerAdvice classes.
  • @ExceptionHandler(TodoNotFoundException.class): This defines that the method to follow will handle the specific exception of TodoNotFoundException.class. Any other exceptions for which custom exception handling is not defined will follow the default exception handling provided by Spring Boot.
  • ExceptionResponse exceptionResponse = new ExceptionResponse(ex.getMessage(), "Any details you would want to add"): This creates a custom exception response.
  • new ResponseEntity<ExceptionResponse>(exceptionResponse,new HttpHeaders(), HttpStatus.NOT_FOUND): This is the definition to return a 404 Not Found response with the custom exception we defined earlier.

When we execute the service with a GET request to a nonexistent todo (http://localhost:8080/users/Jack/todos/222), we get the following response:

    {
"timestamp": 1484030343311,
"message": "Todo Not Found",
"details": "Any details you would want to add"
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset