Servlet Exception and Error Handling Example Tutorial

Filed Under: Java EE

Today we will look into Servlet Exception and Error Handling. Sometime back I wrote a post about Exception Handling in Java but when it comes to web application, we need more than normal exception handling in java.

Servlet Exception

If you notice, doGet() and doPost() methods throw javax.servlet.ServletException and IOException, let’s see what happens when we throw these exception from our application. I will write a simple servlet that will throw the ServletException.


package com.journaldev.servlet.exception;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/MyExceptionServlet")
public class MyExceptionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		throw new ServletException("GET method is not supported.");
	}

}

Now when we invoke this servlet through browser with GET method, we get response like below image.

Servlet Exception, javax.servlet.ServletException

Since browser understand only HTML, when our application throw exception, servlet container processes the exception and generate a HTML response. This logic is specific to servlet container. I am using tomcat and getting this error page. If you will use some other servers like JBoss or Glassfish, you might get different error HTML response.

The problem with this response is that it’s of no value to user. Also it’s showing our application classes and server details to user that makes no sense to user and it’s not good from security point of view.

Servlet Error

I am sure you must have seen 404 error when you are trying to hit a URL that doesn’t exists. Let’s see how our servlet container responds to 404 error. If we send request for an invalid URL, we get response HTML like below image.

Servlet Error

Again it’s a generic HTML generated by server on our application behalf and hold little to no value to the user.

Servlet Exception and Error Handling

Servlet API provides support for custom Exception and Error Handler servlets that we can configure in deployment descriptor. The whole purpose of these servlets are to handle the Exception or Error raised by application and send useful HTML response to user. We can provide link to application home page or some details to let user know what went wrong.

So first of all we need to create a custom Exception and Error Handler servlet. We can have multiple exception and error handler servlets for the application but for simplicity I will create a single servlet and use it for both exceptions and errors.

AppExceptionHandler.java


package com.journaldev.servlet.exception;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/AppExceptionHandler")
public class AppExceptionHandler extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processError(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processError(request, response);
	}

	private void processError(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// Analyze the servlet exception
		Throwable throwable = (Throwable) request
				.getAttribute("javax.servlet.error.exception");
		Integer statusCode = (Integer) request
				.getAttribute("javax.servlet.error.status_code");
		String servletName = (String) request
				.getAttribute("javax.servlet.error.servlet_name");
		if (servletName == null) {
			servletName = "Unknown";
		}
		String requestUri = (String) request
				.getAttribute("javax.servlet.error.request_uri");
		if (requestUri == null) {
			requestUri = "Unknown";
		}
		
		// Set response content type
	      response.setContentType("text/html");
	 
	      PrintWriter out = response.getWriter();
	      out.write("<html><head><title>Exception/Error Details</title></head><body>");
	      if(statusCode != 500){
	    	  out.write("<h3>Error Details</h3>");
	    	  out.write("<strong>Status Code</strong>:"+statusCode+"<br>");
	    	  out.write("<strong>Requested URI</strong>:"+requestUri);
	      }else{
	    	  out.write("<h3>Exception Details</h3>");
	    	  out.write("<ul><li>Servlet Name:"+servletName+"</li>");
	    	  out.write("<li>Exception Name:"+throwable.getClass().getName()+"</li>");
	    	  out.write("<li>Requested URI:"+requestUri+"</li>");
	    	  out.write("<li>Exception Message:"+throwable.getMessage()+"</li>");
	    	  out.write("</ul>");
	      }
	      
	      out.write("<br><br>");
	      out.write("<a href=\"index.html\">Home Page</a>");
	      out.write("</body></html>");
	}
}

Let’s see how we can configure it in deployment descriptor and then we will understand it’s implementation and how it works.


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>ServletExceptionHandling</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  
  <error-page>
  	<error-code>404</error-code>
  	<location>/AppExceptionHandler</location>
  </error-page>
  
  <error-page>
  <exception-type>javax.servlet.ServletException</exception-type>
  <location>/AppExceptionHandler</location>
  </error-page>
</web-app>

As you can see, it’s very easy to specify Exception handler servlets for the application using error-page element. Each error-page element should have either error-code or exception-type element. We define the exception handler servlet in location element.

Based on above configuration, if the application throw 404 error or ServletException, it will be handled by AppExceptionHandler servlet.

When such exception and error scenario appears, servlet container will invoke the corresponding HTTP method of the Exception Handler servlet and pass the request and response object. Notice that I have provided implementation of both doGet() and doPost() methods so that it can handle GET and POST requests and using a common method to process them.

Before servlet container invokes the servlet to handle the exception, it sets some attributes in the request to get useful information about the exception, some of them are javax.servlet.error.exception, javax.servlet.error.status_code, javax.servlet.error.servlet_name and javax.servlet.error.request_uri.

For exception, status code is always 500 that corresponds to the “Internal Server Error”, for other types of error we get different error codes such as 404, 403 etc.

Using the status code, our implementation presents different types of HTML response to the user. It also provides a hyperlink to the home page of the application.

Now when we will hit our servlet that is throwing ServletException, we will get a response like below image.

Servlet Exception, Servlet 500 Internal Server Error

If we try to access an invalid URL that will result in 404 response, we will get response like below image.

Servlet Error, Servlet Error Handling, servlet 404

Doesn’t it look good and helps user to easily understand what happened and provides them a way to go to the correct location. It also avoids sending application sensitive information to the user. We should always have exception handlers in place for our web application.

If you want to handle runtime exceptions and all other exceptions in a single exception handler, you can provide exception-type as Throwable.


<error-page>
  <exception-type>java.lang.Throwable</exception-type>
  <location>/AppExceptionHandler</location>
</error-page>

If there are multiple error-page entries, let’s say one for Throwable and one for IOException and application throws FileNotFoundException then it will be handled by error handler of IOException.

You can also use JSP page as exception handler, just provide the location of jsp file rather than servlet mapping.

That’s all for servlet exception handling in web application, I hope you liked it.

Check out other articles in this series:

  1. Java Web Application
  2. Java Servlet Tutorial
  3. Session Management in Java
  4. Servlet Filter
  5. Servlet Listeners
  6. Cookies in Servlets
  7. Servlet File Upload and Download Example

Comments

  1. bob white says:

    Where do you put the AppExceptionHandler file???

  2. Vedant says:

    Good resources for web development. Thanks mate.

  3. Jethruel Bustamante says:

    I just want to ask for help on how to trap the same data entered in the database using java servlet code….tnx in advance and merry christmas!!!

  4. I very thankful to your website .this is very much helpful to me .and i leran ervery thing in java easily

  5. Madhavi says:

    I am trying to integrate hibernate with jsp servlet in a web application. The servlet does not show any error, but it generates a BLANK PAGE in the browser.
    When I removed a single line of code (whose purpose was, to call a method to insert data into sql table) then it was showing output.
    Please Help. No amount of Google-ing could solve it.

    1. gowtham says:

      Actually i am also encountered same problem, it always shows me blank page after 2 hr hard work i found problem where it is the thing is annotations are not working properly in tomcat 6.0 because tomcat lib have a servlet-api.jar again we place javax-servlet-api.jar file in webapp’s . so it’s raises error.

      1. Pankaj says:

        Use Tomcat 7 or higher.

  6. James Livingston says:

    It would be better to override service() rather than doGet() and doPost(), so it handles all HTTP methods and not just GET/POST. As-is, if there is an error for other methods it will result in a Method Not Allowed error from the error page, which on most servlet contains will result in a blank page or a nasty error page.

    1. Pankaj says:

      No we should not override service() method, best approach is to override the doGet(), doPost() methods.

  7. JOTHIBASU says:

    Very Useful to learn servlet Exception .

  8. Ehan Rawh says:

    Need Help badly:
    I always get this error when I try to use a XMPP based support system running in Java (Tomcat). The application does not require any database to run. Couldn’t find any solution.
    —————————————————

    HTTP Status 500 – Server does not support account creation.:

    type Exception report

    message Server does not support account creation.:

    description The server encountered an internal error (Server does not support account creation.: ) that prevented it from fulfilling this request.

    exception

    javax.servlet.ServletException: Server does not support account creation.:
    msg.jabber.web.InitChat.doPost(InitChat.java:83)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:170)
    root cause

    Server does not support account creation.:
    org.jivesoftware.smack.AccountManager.createAccount(AccountManager.java:185)
    msg.jabber.chat.Messenger.(Messenger.java:45)
    msg.jabber.chat.Manager.getMessenger(Manager.java:51)
    msg.jabber.web.InitChat.doPost(InitChat.java:61)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:170)

  9. Gerry Matte says:

    I implemented your code and am very pleased with the results. I am using the AppExceptionHandler to store log records in a database. I mapped 7 error codes plus the ServletException to /AppExceptionHandler.

    Using eclipse (kepler) with a maven project, I see within the web.xml eight eclipse warnings that “location references to “/AppExceptionHandler” that does not exist in web content.

    The application functions without any problems including trapping exceptions and error pages.

    Any idea how I might eliminate the warnings ?

    BTW, thank you very much for publishing this well written article …. I’ll be using this new tool in all my future webapps.

    1. Gerry Matte says:

      Resolved.

      The eclipse web.xml editor is unable to resolve servlet references that are defined using the @WebServlet annotation on the class.

      If you remove the annotation and instead declare the servlet and servet-mapping within web.xml, the warnings disappear.

    2. Pankaj says:

      Maven Project – Did you added dependencies in pom.xml? Try to update Maven Project once.

      Also how are you running the application, through Tomcat in Eclipse or are you exporting as WAR to tomcat server at some location.

  10. small links says:

    Magnificent points altogether, you just gained a emblem new reader. What could you recommend about your publish that you made a few days ago? Any sure?

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages