Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring 3 MVC Exception Handlers and @ResponseStatus

DZone's Guide to

Spring 3 MVC Exception Handlers and @ResponseStatus

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

My last couple of blogs have covered Spring’s MVC @ExceptionHandler annotation outlining where and why you should use it. Today’s blog wraps up the discussion on the basics of @ExceptionHandler by taking a look at the companion annotation @ResponseStatus. To get started, I’m going to dive into a simple scenario where a user sends a request containing some duff data to your webapp. Your webapp can’t deal with this and throws a DataFormatException as demonstrated by the simple controller method below:

  @RequestMapping(value = "/dataformat", method = RequestMethod.GET)
  public String throwDataFormatException(Locale locale, Model model)
      throws DataFormatException {

    logger.info("This will throw a DataFormatException");

    boolean throwException = true;

    if (throwException) {
      throw new DataFormatException("This is my DataFormatException");
    }

    return "home";
  }

The next part of the scenario is where you catch the exception making a note in the log, and changing the HTTP status code to 404 not found. This is demonstrated by the code below:
  @ExceptionHandler(DataFormatException.class)
  @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "My Response Status Change….!!")
  public void handleDataFormatException(DataFormatException ex,
      HttpServletResponse response) {

    logger.info("Handlng DataFormatException - Catching: "
        + ex.getClass().getSimpleName());
  }

There are several differences between this exception handler and the ones shown in my previous blogs. Firstly, the @ResponseStatus line has been added:

  @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "My Response Status Change....!!")

This takes two arguments. The default, or value, argument is used to alter the status code sent back the server and client. This is defined in Spring’s HttpStatus enum, which I suspect maps the enum values back to their original integer codes. The other optional argument is the reason argument and it’s used to provide a message for the caller.

The next difference between this exception handler and the fine-tuned example I demonstrated in my previous blogs is that this method does nothing except log an error. Experience shows that once you muck about with the HTTP status value, Tomcat steps in and intercepts your response to the browser. If you change the status to 200 (OK) you get a blank page, whilst any other value displays the default Tomcat error page as shown below:


The fix to this would be to map this this reposne to one of your own pages by modifying your web.xml file.

The fine-grained approach to error handling is achieved by Spring's AnnotationMethodHandlerExceptionResolver an ‘under the hood’ class that implements their HandlerExceptionResolver interface. Fine-grained error handling, however, won’t fulfill all your needs and there will be those times when you need to operate using a coarse grained approach, capturing exceptions from multiple controllers in a single place. This is where another HandlerExceptionResolver implementation comes in to play, one that simply maps all your exceptions to a single handler class. I guess that’s why the Guys at Spring called it SimpleMappingExceptionResolver, but more on that another day.


  1. The full webapp sample is available at:

    git://github.com/roghughe/captaindebug.git
  2. See the Spring documentation for reference material.

 

From http://www.captaindebug.com/2012/02/spring-3-mvc-exception-handlers-and_14.html

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}