Error Handling for REST with Spring

I usually post about REST APIs and HTTP on Twitter - you can follow me there:

Table of Contents

1. Overview

This article will illustrate how to implement Exception Handling with Spring for a REST API. We’ll look at both the recommended solution with Spring 3.2 and 4.x but also at the older options as well.

Before Spring 3.2, the two main approaches to handling exceptions in a Spring MVC application were: HandlerExceptionResolver or the @ExceptionHandler annotation. Both of these have some clear downsides.

After 3.2 we now have 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 app can throw exception normally to indicate a failure of some kind – exceptions which will then be handled separately.

2. Solution 1 – The Controller level @ExceptionHandler

The first solution works at the @Controller level – we will define a method to handle exceptions, and annotate that with @ExceptionHandler:

public class FooController{
    @ExceptionHandler({ CustomException1.class, CustomException2.class })
    public void handleException() {

This approach has a major drawback – the @ExceptionHandler annotated method is only active for that particular Controller, not globally for the entire application. Of course adding this to every controller makes it not well suited for a general exception handling mechanism.

The limitation is often worked around by having all Controllers extend a Base Controller class – however, this can be a problem for applications where, for whatever reasons, the Controllers cannot be made to extend from such a class. For example, the Controllers may already extend from another base class which may be in another jar or not directly modifiable, or may themselves not be directly modifiable.

Next, we’ll look at another way to solve the exception handling problem – one that is global and does not include any changes to existing artifacts such as Controllers.

3. Solution 2 – The HandlerExceptionResolver

The second solution is to define an HandlerExceptionResolver – this will resolve any exception thrown by the application. It will also allow us to implement a uniform exception handling mechanism in our REST API.

Before going for a custom resolver, let’s go over the existing implementations.

3.1. ExceptionHandlerExceptionResolver

This resolver was introduced in Spring 3.1 and is enabled by default in the DispatcherServlet. This is actually the core component of how the @ExceptionHandler mechanism presented earlier works.

3.2. DefaultHandlerExceptionResolver

This resolver was introduced in Spring 3.0 and is enabled by default in the DispatcherServlet. It is used to resolve standard Spring exceptions to their corresponding HTTP Status Codes, namely Client error – 4xx and Server error – 5xx status codes. Here is the full list of the Spring Exceptions it handles, and how these are mapped to status codes.

While it does set the Status Code of the Response properly, one limitation is that it doesn’t set anything to the body of the Response. And for a REST API – the Status Code is really not enough information to present to the Client – the response has to have a body as well, to allow the application to give additional information about the failure.

This can be solved by configuring View resolution and rendering error content through ModelAndView, but the solution is clearly not optimal – which is why a better option has been made available with Spring 3.2 – we’ll talk about that in the latter part of this article.

3.3. ResponseStatusExceptionResolver

This resolver was also introduced in Spring 3.0 and is enabled by default in the DispatcherServlet. It’s main responsibility is to use the @ResponseStatus annotation available on custom exceptions and to map these exceptions to HTTP status codes.

Such a custom exception may look like:

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public final class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException() {
    public ResourceNotFoundException(String message, Throwable cause) {
        super(message, cause);
    public ResourceNotFoundException(String message) {
    public ResourceNotFoundException(Throwable cause) {

Same as the DefaultHandlerExceptionResolver, this resolver is limited in the way it deals with the body of the response – it does map the Status Code on the response, but the body is still null.

3.4. SimpleMappingExceptionResolver and AnnotationMethodHandlerExceptionResolver

The SimpleMappingExceptionResolver has been around for quite some time – it comes out of the older Spring MVC model and is not very relevant for a REST Service. It is used to map exception class names to view names.

The AnnotationMethodHandlerExceptionResolver was introduced in Spring 3.0 to handle exceptions through the @ExceptionHandler annotation, but has been deprecated by ExceptionHandlerExceptionResolver as of Spring 3.2.

3.5. Custom HandlerExceptionResolver

The combination of DefaultHandlerExceptionResolver and ResponseStatusExceptionResolver goes a long way towards providing a good error handling mechanism for a Spring RESTful Service. The downside is – as mentioned before – no control over the body of the response.

Ideally, we’d like to be able to output either JSON or XML, depending on what format the client has asked for (via the Accept header).

This alone justifies creating a new, custom exception resolver:

public class RestResponseStatusExceptionResolver extends AbstractHandlerExceptionResolver {

    protected ModelAndView doResolveException
      (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        try {
            if (ex instanceof IllegalArgumentException) {
                return handleIllegalArgument((IllegalArgumentException) ex, response, handler);
        } catch (Exception handlerException) {
            logger.warn("Handling of [" + ex.getClass().getName() + "] 
              resulted in Exception", handlerException);
        return null;

    private ModelAndView handleIllegalArgument
      (IllegalArgumentException ex, HttpServletResponse response) throws IOException {
        String accept = request.getHeader(HttpHeaders.ACCEPT);
        return new ModelAndView();

One detail to notice here is the Request itself is available, so the application can consider the value of the Accept header sent by the client. For example, if the client asks for application/json then, in case of an error condition, the application should still return a response body encoded with application/json.

The other important implementation detail is that a ModelAndView is returned – this is the body of the response and it will allow the application to set whatever is necessary on it.

This approach is a consistent and easily configurable mechanism for the error handling of a Spring REST Service. It is does however have limitations: it’s interacting with the low level HtttpServletResponse and it fits into the old MVC model which uses ModelAndView – so there’s still room for improvement.

4. Solution 3 – The New @ControllerAdvice (Spring 3.2 And Above)

5. Conclusion

This tutorial discussed several ways to implement an exception handling mechanism for a REST API in Spring, starting with the older mechanism and continuing with the Spring 3.2 support and into 4.0 and 4.1.

The implementation of this Spring Error Handling for REST article can be downloaded as a working sample project.

It’s an Eclipse based project, so it should be easy to import and run as it is.

I usually post about REST APIs and HTTP on Twitter - you can follow me there:

Get the eBooks and Learn to Build a Simple App
Build a Simple but Working App with Spring


  • Federico

    This has been quite helpful but I think there’s a missing piece. To write content when access is denied I had to configure the app like this:


    • Eugen Paraschiv

      These techniques are mainly security agnostic. In the case of a Spring Security enabled application, I’ll take a crack at an example soon and follow up on this thread.

      • Eric B

        @baeldung:disqus Have you had a chance to put together a Spring Security example yet for exception handling? I too have only come up with the solution presented by @Federico but would like to find something more central that I can use as a resolver as opposed to having a resolver for my MVC component and a Handler for my security component.

        • Eugen Paraschiv

          Not yet Eric – I’m planning to work on that at some point, but haven’t had to much time to write lately. I’m hopping to get to it soon. Cheers,

  • Rodislav Moldovan

    for REST api’s I usually create special class called [Response] with 3 fields, isError, message, data, in other cases I write the error messages through the modelView directly into page

    usually, I don’t use generic handlers, but after reading this post I think I’ll give them a try

    • Eugen Paraschiv

      In my view – they’re not mutually exclusive – in fact, instead of the simple “This should be application specific” String, I use a very similar class – I have yet to write about it, but basically it replaces that String.
      Let me know how using the generic handler goes for you.

  • Amit Ghorpade

    I have two packages for controllers as v1 and v2 package which support version. I have controllerAdvice to support global exception handling.
    How i can apply ControllerAdvice specific to package level controllers? for example v1 controller excetions should be handled by v1ControllerAdvice and for v2 it should be by v2ControllerAdvice.

    • Amit Ghorpade

      Found the solution spring 4.0 comes with solution for package wise controlleradvice
      We can mention @ControllerAdvice(basePackages=”″) for controller which are inside in v1 package

  • Bill

    Eugen – these blogs are extremely useful! I’ve been using spring for years but have resisted bringing myself up to date. I’m impressed by the example code which actually works (not typical of blogs and posts).

    • Eugen Paraschiv

      Hey Bill – glad they’re helping. Yes – the code really should work – I’m updating it regularly. There may of course be instances where I miss something – in which case – do let me know and it will get fixed quickly. Cheers,

  • Ignacio Cañon

    Hi, first of all thank you for your blog, nice job!
    Regarding this exception-handling subject I’m not sure if I’m doing any wrong with my code, I’ve been reading your blog and other ones searching for how to handle Spring Security Exceptions, and I found several times that I could use a @ControllerAdvice to handle those exceptions, but It’s now working for me (Spring 4.2), it’s like it would only work for exceptions thrown by Controllers, despite you say It can be used for global Exceptions in the Web App.

    No Spring filter exception is handled by the moment.
    Did I miss something?

    • Eugen Paraschiv

      Hey Ignacio – glad you like the blog. First – Spring 4.2 – are you using snapshots (it’s not out yet)? Second – you might have a problem with which context your beans are defined in (if you’re using multiple contexts). The sample project has a fully working solution, so you can look at where beans are being defined and how exceptions are being thrown in there.
      Hope it helps. Cheers,

  • ChangWonSon

    I have question
    Error handling with @ControllerAdvice, Spring 4.1.1, tomcat
    almost error is caught by @ExceptionHandler
    but only 404 NOT FOUND is impossible by ExceptionHandler
    what should I do for handling 404 error

    • Eugen Paraschiv

      Hey Chang, I’m not sure I follow what you’re asking here, can you please re-phrase it? Cheers,

      • ChangWonSon

        my GlobaExceptionHaldler class use @ControllerAdvice and extends ResponseEntityExceptionHandler
        and Override two method
        1.ResponseEntityExceptionHandler.handleNoHandlerFoundException( …)
        2.ResponseEntityExceptionHandler.handleNoSuchRequestHandlingMethod( …)

        but I was not working
        if request uri is not valid (ex> localhost/uriNotExists) <- this is 404 not found
        GlobalExceptionHandler not catched exception

        • Eugen Paraschiv

          Well, it might be that the bean isn’t registered in the context; it might be that it’s registered in the wrong context or any number of other things. Not sure what the problem is from the limited info above – is there a github project I can look at? Cheers,

          • Sam

            I’ve the same problem too, so what does you mean? the bean isn’t registered in the context. Please detail it.

          • Eugen Paraschiv

            Hey Sam, as I was saying above, it’s not possible to diagnose a problem from a rough description like that. If there’s a github project you can point me to, I’d be happy to take a look. Cheers, Eugen.