7

I am writing a servlet, in that if any exception occurs i donэt want to display exception/error message on browser, so I will redirect to my customized error page. So I have done like this:

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
try{
    //Here is all code stuff
}catch(Exception e){

  request.getRequestDispatcher("/ErrorPage.jsp").forward(request, response);
  e1.printStackTrace();

}

Is this the correct way, if I am wrong please correct me and if there is any better mechanism please tell me.

Roman C
  • 49,761
  • 33
  • 66
  • 176
Raghu
  • 1,324
  • 7
  • 24
  • 47
  • Duplicate of http://stackoverflow.com/q/7066192 Performing forward() as in your snippet and in the answer below is at least wrong. If you really want to do it programmatically, you should be using sendError(), not forward(). – BalusC Jul 01 '16 at 07:25

3 Answers3

7

Only way to handle it in a generic way is to use web.xml like below:

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

The servlet is thrown ServletException and IOException but if you want to handle runtime exceptions and all other exceptions in a single exception handler, you can provide exception-type as Throwable. You can use multiple error-page entries that will handle different type of exceptions and have different handlers.

Example:

@WebServlet("/ErrorHandler")
public class ErrorHandler 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 {
        //customize error message
        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";
        }    
        request.setAttribute("error", "Servlet " + servletName + 
          " has thrown an exception " + throwable.getClass().getName() +
          " : " + throwable.getMessage());    
        request.getRequestDispatcher("/ErrorPage.jsp").forward(request, response);
    }
}
Roman C
  • 49,761
  • 33
  • 66
  • 176
  • 1
    Thank u , So now what should be in `catch` block and `ErrorHandler` Servlet.? Can u please show me with small example code. – Raghu Nov 10 '14 at 05:00
  • In the catch block you can forward to `/ErrorHandler` instead of error page. The example of error handler servlet I have posted. – Roman C Nov 10 '14 at 09:39
  • oh . . Thank U ,& How can I print `statusCode`, `throwable` object in jsp page. – Raghu Nov 10 '14 at 10:00
  • `${statusCode}` and `${throwable}` – Roman C Nov 10 '14 at 10:02
  • I m not getting the values in jsp , but the values get printed If I print it in servlet from `out.prinln()`. – Raghu Nov 10 '14 at 10:31
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/64618/discussion-between-raghu-and-roman-c). – Raghu Nov 10 '14 at 10:45
  • No .., now also I m not getting should I use <%@page isErrorPage="true"%> – Raghu Nov 10 '14 at 10:47
  • @RomanC nice solution. However, this is also going to leave /ErrorHandler open for access right? (i.e. a user can directly visit http:////ErrorHandler). What if I do not want to expose this endpoint but still want to achieve the same error handling effect as current solution? – torez233 Nov 03 '21 at 04:52
  • @torez233 If you don't want to expose this endpoint then protect it with the best of security can apply. – Roman C Nov 03 '21 at 14:52
2

In some method, you would have the following:

try {
  // something
} catch (Exception e) {
  sendErrorRedirect(req, res, "/errorpage.jsp", e);
}

// then....  sendErrorRedirect looks like this:
  protected void sendErrorRedirect(HttpServletRequest request, HttpServletResponse response, String errorPageURL, Throwable e) {
      try {
            request.setAttribute ("javax.servlet.jsp.jspException", e);
            getServletConfig().getServletContext().getRequestDispatcher(errorPageURL).forward(request, response);
      } catch (Exception ex) {
            putError("serXXXXX.sendErrorRedirect ", ex);
      }
  }
  • Thank u , it s for one servlet , v can write a method like this , but we cant write this method for every servlet rt? I have somany servlets . – Raghu Nov 10 '14 at 05:12
2

One way to handle it in a generic way is to use web.xml like below:

<error-page>
    <exception-type>java.io.IOException</exception-type >
    <location>/ErrorHandler</location>
</error-page>

I have just included IO exception but you might have say SQLException you could very well add another error-page and another location for the same. Similarly you could say java.lang.Exception type and one handler handling everything.

SMA
  • 36,381
  • 8
  • 49
  • 73