O'Reilly logo

Spring MVC Cookbook by Alex Bretet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required