Skip to main content

REST tutorial : error handling

Greetings!

So far we have neglected error scenarios in our API. Any application without proper error handling is a disaster.

You can find the complete source code here Todoapp

Try these URLs and see the output.
http://localhost:8080/todoss
http://localhost:8080/todos/abcd

Spring has handled errors for us!! but the messages are not interesting enough.

Global exception handling

  • With Spring's @ControllerAdvice we can handle exception globally. 
  • ResponseEntityExceptionHandler : A convenient base class for @ControllerAdvice classes that wish to provide centralized exception handling across all @RequestMapping methods through @ExceptionHandler methods. 
  • @RestControllerAdvice is a new feature of Spring Framework 4.3, an annotation with combined @ControllerAdvice + @ResponseBody
  • Enable spring.mvc.throw-exception-if-no-handler-found to customize 404 error

Note that our TodoService is also updated to throw a custom exception.
See the complete code in error-handling branch.

In next part of the tutorial we are going to add validation to Todo itself.

Comments