Overview

This tutorial will illustrate how to implement Exception Handling with Spring for a REST API

Before Spring 3.2, the two main approaches to handling exceptions in a Spring MVC application were HandlerExceptionResolver or the @ExceptionHandler annotation.

Since 3.2, we’ve had the @ControllerAdvice annotation to address the limitations of the previous two solutions and to promote a unified exception handling throughout a whole application. Now Spring 5 introduces the ResponseStatusException class — a fast way for basic error handling in our REST APIs.

⇒ All of these do have one thing in common: They deal with the separation of concerns very well. The app can throw exceptions normally to indicate a failure of some kind, which will then be handled separately.

Solutions:

Conclusion

Each of these solutions has its own use case. For handling exceptions specific to a controller, @ExceptionHandler is a good choice. For global exception handling, @ControllerAdvice is more suitable. If you need more control over the exception handling process, consider implementing HandlerExceptionResolver. Finally, ResponseStatusException provides a quick and straightforward way to handle exceptions in REST APIs starting from Spring 5.


Handle the Access Denied in Spring Security

6.1. REST and Method-Level Security