13

How do you properly handle errors encountered in a servlet? Right now, the app that I inherited (uses only plain JSP/Servlet) has a superclass called Controller which extends HttpServlet and which all other servlets extend from. In that Controller class is a try and catch block like the following:

try {
    // execute doPost or doGet here
} catch (Exception e) {
    // show a generic error page
}

Is this the proper way of doing it? It seems clunky and doesn't seem to always work. I'm only an intern so I don't have a lot of experience with this. Any advice? I'm trying to make the app for robust..

Damian Wells
  • 133
  • 1
  • 1
  • 6
  • [A related question that gives an example of handling exceptions in a filter](http://stackoverflow.com/questions/11245932/how-to-handle-exceptions-thrown-while-rendering-a-view-in-spring-mvc), which is another option in addition to the answer below (that question is in the context of Spring but still applies). – Jason C Aug 30 '16 at 14:31

4 Answers4

17

The standard thing to do is have your Servlet's doXxx() method (eg. doGet(), doPost(), etc.) throw a ServletException and allow the container to catch and handle it. You can specify a custom error page to be shown in WEB-INF/web.xml using the <error-page> tag:

<error-page>
    <error-code>500</error-code>
    <location>/error.jsp</location>
</error-page>

If you end up catching an Exception you can't elegantly handle, just wrap it in a ServletException like this:

try {
    // code that throws an Exception
} catch (Exception e) {
    throw new ServletException(e);
}
Asaph
  • 159,146
  • 25
  • 197
  • 199
  • Oh, I thought was only for handling exceptions encountered in JSPs. – Damian Wells May 31 '11 at 04:08
  • 5
    @Damian: in contrary, exceptions should be handled in servlets, far before any bit is being written to the response. Throwing exceptions in JSPs and thus abruptly aborting its flow would only risk the response ending up in a blank page and/or halfbaked HTML because JSP may already be in midst of sending the response which is a point of no return. – BalusC May 31 '11 at 04:15
  • What's the added value of wrapping the exception into a ServletException? – geschema Oct 29 '17 at 14:22
  • 1
    @geschema You'll gain some default exception handling from the Servlet container such as displaying an html error page to the user and logging the exception stack trace for later debugging. – Asaph Oct 29 '17 at 19:32
  • 1
    OK that makes sense. Thanks @Asaph – geschema Oct 30 '17 at 13:49
17

Or you can intercept all your exceptions using a servlet:

<!-- WEB-INF/web.xml -->
<servlet>
    <servlet-name>ErrorServlet</servlet-name>
    <servlet-class>com.domain.MyErrorServlet</servlet-class>
</servlet>    
<servlet-mapping>
<servlet-name>ErrorServlet</servlet-name>
    <url-pattern>/error</url-pattern>
</servlet-mapping>
<error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/error</location>
</error-page>

Then in the servlet you can handle the exception like this

public class MyErrorServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response){
       Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
       // You can log the exception, send to email, etc
    }
}
Don Grem
  • 1,257
  • 3
  • 17
  • 25
2

There are a few best practices when it comes to exceptions. Generally you can either handle it, let it bubble up(for unchecked exceptions), log it, or wrap it.

You should avoid catching and throwing exception, instead catch the more specific exception, or create your own exception type and wrap the current exception in that.

Heres a great resource to use as a "What not to do" in terms of exceptions: http://today.java.net/article/2006/04/04/exception-handling-antipatterns

Dimitar
  • 2,392
  • 2
  • 19
  • 28
1

In JSP you can use jstl core library

1) Import tablib on top of JSP file

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

2) use tag

<c:catch var="myExceptionObject">
    Code that might throw Exception
</c:catch>

<c:if test="${myExceptionObject} != null">
    There was an exception: ${myExceptionObject.message}
</c:if>
Archangel1C
  • 100
  • 11