handle exceptions thrown by application

handle exceptions thrown by application

In a web application, it’s important to handle exceptions gracefully to ensure a good user experience and maintain application stability. One way to handle exceptions in a Java Servlet-based web application is to use an error handling servlet. This servlet can capture exceptions thrown by other servlets and provide appropriate responses or error pages.

handle exceptions

Here’s how you can handle exceptions using another servlet:

1. Define Error Pages in web.xml

You can specify error pages for specific exceptions or HTTP error codes in your web.xml file. When an exception occurs, the specified error page (which can be a servlet, JSP, or static HTML) will be invoked.

    Example: In web.xml, define error pages for exceptions and error codes:

    Example
    
    xml
    <web-app>
      <!-- Define error page for a specific exception -->
      <error-page>
        <exception-type>java.lang.Throwable</exception-type>
        <location>/errorHandler</location>
      </error-page>
    
      <!-- Define error page for a specific HTTP error code -->
      <error-page>
        <error-code>404</error-code>
        <location>/errorHandler</location>
      </error-page>
    </web-app>
    

    In this example, any unhandled exception (java.lang.Throwable) or HTTP 404 error will be redirected to /errorHandler.

    2. Create an Error Handling Servlet

    Create a servlet that will handle the errors. This servlet can log the error, notify the user, or redirect to a more user-friendly error page.

      Create an ErrorHandlerServlet:
      java
      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("/errorHandler")
      public class ErrorHandlerServlet extends HttpServlet {
          private static final long serialVersionUID = 1L;
      
          @Override
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              handleException(request, response);
          }
      
          @Override
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              handleException(request, response);
          }
      
          private void handleException(HttpServletRequest request, HttpServletResponse response) throws IOException {
              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");
              String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");
      
              if (servletName == null) {
                  servletName = "Unknown";
              }
              if (requestUri == null) {
                  requestUri = "Unknown";
              }
      
              // Log the error (could be replaced with a logging framework)
              System.err.println("Servlet Name: " + servletName);
              System.err.println("Exception: " + throwable);
              System.err.println("Request URI: " + requestUri);
              System.err.println("Status Code: " + statusCode);
      
              // Set response content type
              response.setContentType("text/html");
      
              // Generate the error page
              response.getWriter().println("<html><head><title>Error Page</title></head><body>");
              if (statusCode != 500) {
                  response.getWriter().println("<h3>Error Code: " + statusCode + "</h3>");
              } else {
                  response.getWriter().println("<h3>Exception: " + throwable.getMessage() + "</h3>");
              }
              response.getWriter().println("<p>Servlet Name: " + servletName + "</p>");
              response.getWriter().println("<p>Request URI: " + requestUri + "</p>");
              response.getWriter().println("</body></html>");
          }
      }
      

      3. Triggering Exceptions

      For demonstration purposes, you might want to create a servlet that deliberately throws an exception:

        Example: Create a servlet that throws an exception:

        Example
        
        
        java
        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("/triggerError")
        public class ErrorTriggerServlet extends HttpServlet {
            private static final long serialVersionUID = 1L;
        
            @Override
            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                throw new ServletException("Deliberate Exception for Testing");
            }
        }
        

        Summary

        To handle exceptions in a servlet-based application with another servlet:

        • Define error pages in web.xml for specific exceptions and HTTP error codes.
        • Create an error handling servlet to log the error and provide a user-friendly response.
        • Test by creating a servlet that triggers exceptions.

        By following these steps, you can ensure that your application handles errors gracefully and provides useful feedback to users.

        Homepage

        Readmore