Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to error page when exception occurs from servlet?

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.

like image 464
Raghu Avatar asked Nov 07 '14 12:11

Raghu


People also ask

How can a servlet call a error page?

If any type of exception occurs while executing an action, the servlet catches it, sets the javax. servlet. jsp. jspException request attribute to the exception object, and forwards the request to the error JSP page.

How do you handle exceptions thrown by another servlet in an application?

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.

Which tag in JSP is used to redirect to the error page?

A JSP page can specify its own default error JSP page from an exception that is occurring within it, through the JSP error tag. This enables a JSP page to specify its own handling of an error.

How do I redirect a servlet page in HTML?

The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file. It accepts relative as well as absolute URL. It works at client side because it uses the url bar of the browser to make another request.


2 Answers

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);
    }
}
like image 166
Roman C Avatar answered Sep 26 '22 21:09

Roman C


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);
      }
  }
like image 39
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Avatar answered Sep 24 '22 21:09

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa