1. Overview

This article will focus on how to implement Exception Handling with Spring for a REST API. We’ll look at the older solutions available before Spring 3.2 and then at the new Spring 3.2 support.

The main goal of this article is to show how to best map Exceptions in the application to HTTP Status Codes. Which status codes are suitable for which scenarios is not in the scope of this article, neither is the syntax of REST Error Representation.

The REST with Spring series:

Before Spring 3.2, the two main approaches to handling exceptions in a Spring MVC application were: HandlerExceptionResolver and the @ExceptionHandler annotation. Spring 3.2 introduced the new @ControllerAdvice annotation to address the limitations of the previous two solutions.

All of these do have one thing in common – they deal with the separation of concerns very well: the standard application code can throw exception normally to indicate a failure of some kind – exceptions which will then be handled via any of the following.

2. Via Controller level @ExceptionHandler

Defining a Controller level method annotated with @ExceptionHandler is very easy:

public class FooController{    ...    

   @ExceptionHandler({ CustomException1.class, CustomException2.class })

    public void handleException() {        //    }

}

That’s all well and good, but this approach does have one major drawback – the @ExceptionHandler annotated method is only active for that particular Controller, not glabally for the entire application. Of course, this makes it not well suited for a generic exception handling mechanism.

Read the Full Article.