質問

I implemented an UncaughtExceptionHandler on StartUp of tomcat:

 Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            LOGGER.error("Uncaught Exception");
            }
    });

When I produce an Exception in a Servlet it is not caught by my Handler:

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
    int i = 1/0;

The console says:

Feb 13, 2014 8:23:58 AM org.apache.catalina.core.StandardWrapperValve invoke Schwerwiegend: Servlet.service() for servlet [ConnectGatewaysServlet] in context with path [/infraview] threw exception java.lang.ArithmeticException: / by zero at net.test.gateway.ConnectGatewaysServlet.doPost(ConnectGatewaysServlet.java:73) at javax.servlet.http.HttpServlet.service(HttpServlet.java:647) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

How do I implement an UncaughtExceptionHandler for Servlets?

役に立ちましたか?

解決

That's normal. Tomcat has more than a hundred threads, and the uncaught exception handlers are associated to a given thread (it's coming from the time of ThreadGroups).

What you can do is to wrap the contents of the doPost() in a try-catch block.

The other way is to define error handling in the web.xml - you can also create a servlet for handling errors in other servlets :-) See an example here.

他のヒント

I found the below example in a website, thought this refers to exactly your question http://www.journaldev.com/1973/servlet-exception-and-error-handling-example-tutorial

Java Code:

 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>");
    }
}

WEB.XML ERROR HANDLING:

<?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>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top