Handling exceptions globally

This recipe presents a technique for handling exception globally in a web application.

Getting ready

There are different ways to handle exceptions in Spring MVC. We can choose to define controller-specific @ExceptionHandler or we can choose to register @ExceptionHandler globally in the @ControllerAdvice classes.

We developed the second option in our REST API, even if our CloudstreetApiWCI super-class could have shared @ExceptionHandler among its controllers.

Now we will see how to automatically map custom and generic exception types to HTTP status codes, and how to wrap the right error messages in a generic response object that can be used by any client.

How to do it...

  1. We need a wrapper object to be sent back to the client ...

Get Spring MVC: Designing Real-World Web Applications now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.