Home » Java » Enterprise Java » HOW-TO: Custom error pages in Tomcat with Spring MVC

About Rafal Borowiec

Rafal is an IT specialist with about 8 years of commercial experience, specializing in software testing and quality assurance, software development, project management and team leadership. He is currently holding a position of a Team Leader at Goyello where he is mainly responsible for building and managing teams of professional developers and testers. He is also responsible for maintaining relations with customers and acquiring new ones, mainly through consultancy. He believes in Agile project management and he is a big fan of technology, especially Java related (but not limited too). He likes sharing knowledge about software development and practices, through his blog (blog.codeleak.pl) and Twitter (@kolorobot) but also on internal and external events like conferences or workshops.

HOW-TO: Custom error pages in Tomcat with Spring MVC

Default Tomcat error pages look scary. In addition, they may expose valuable information including server version and exception stack trace. Servlet specification provides a way to configure an exceptional behavior through web.xml. One can configure either reaction on a specific Java exception or to a selected Http response code(s).

error-page element specifies a mapping between an error code or exception type to the path of a resource in the Web application:
 
 
 

<web-app>
  
 <!-- Prior to Servlet 3.0 define either an error-code or an exception-type but not both -->
 <error-page>
  <!-- Define error page to react on Java exception -->
  <exception-type>java.lang.Throwable</exception-type>
  <!-- The location of the resource to display in response to the error will point to the Spring MVC handler method -->
  <location>/error</location>
 </error-page>
 
 <error-page>
  <error-code>404</error-code>
  <location>/error</location>
 </error-page>
  
 <!-- With Servlet 3.0 and above general error page is possible -->
 <error-page>
  <location>/error</location>
 </error-page>
 
</web-app>

Having the custom error pages defined in our web.xml, we need to add the Spring MVC @Controller. The customError handler method wraps the information, that we retrieve from the request, and returns it to the view.

@Controller
class CustomErrorController {

 @RequestMapping("error") 
 public String customError(HttpServletRequest request, HttpServletResponse response, Model model) {
  // retrieve some useful information from the request
  Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
  Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
  // String servletName = (String) request.getAttribute("javax.servlet.error.servlet_name");
  String exceptionMessage = getExceptionMessage(throwable, statusCode);

  String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");
  if (requestUri == null) {
   requestUri = "Unknown";
  }

  String message = MessageFormat.format("{0} returned for {1} with message {3}", 
   statusCode, requestUri, exceptionMessage
  ); 

  model.addAttribute("errorMessage", message);  
  return "customError";
 }

 private String getExceptionMessage(Throwable throwable, Integer statusCode) {
  if (throwable != null) {
   return Throwables.getRootCause(throwable).getMessage();
  }
  HttpStatus httpStatus = HttpStatus.valueOf(statusCode);
  return httpStatus.getReasonPhrase();
 }
}

The produced message may look like following: 404 returned for /sandbox/bad with message Not Found.

To see the code in action, browse the source code of  Spring MVC Quickstart Archretype, or even better, generare a new project with it.
 

Reference: HOW-TO: Custom error pages in Tomcat with Spring MVC from our JCG partner Rafal Borowiec at the Codeleak.pl blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*


9 − one =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Do you want to know how to develop your skillset and become a ...

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!
Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close