DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring 3 MVC Exception Handlers and @ResponseStatus

Spring 3 MVC Exception Handlers and @ResponseStatus

Roger Hughes user avatar by
Roger Hughes
·
Feb. 17, 12 · Interview
Like (0)
Save
Tweet
Share
31.24K Views

Join the DZone community and get the full member experience.

Join For 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

Spring Framework

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • OWASP Kubernetes Top 10
  • Secure APIs: Best Practices and Measures
  • 5 Software Developer Competencies: How To Recognize a Good Programmer
  • Java Code Review Solution

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: