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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.