代码之家  ›  专栏  ›  技术社区  ›  Felix Schmidt

如何在Servlet中使用UnaughtExceptionHandler

  •  3
  • Felix Schmidt  · 技术社区  · 11 年前

    我在tomcat的StartUp上实现了UnaughtExceptionHandler:

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

    当我在Servlet中生成异常时,它不会被我的处理程序捕获:

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

    控制台显示:

    2014年2月13日上午8:23:58 org.apache.catalina.core.StandardWrapperValve调用 Schwerwiegend:路径为[/infraview]的上下文中的Servlet[ConnectGatewaysServlet]的Servlet.service()引发异常 java.lang.AithmeticException:/byzero 在net.test.gateway.ConnectGatewaysServlet.doPost(ConnectGatewaysSservlet.java:73) 位于javax.servlet.http.HttpServlet.service(HttpServlet.java:647) 位于javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

    如何为Servlet实现UnaughtExceptionHandler?

    2 回复  |  直到 11 年前
        1
  •  4
  •   rlegendi    11 年前

    这很正常。Tomcat有100多个线程,未捕获的异常处理程序与给定的线程相关联(它来自 ThreadGroups ).

    您可以做的是包装 doPost() 在一个 try-catch

    另一种方法是在 web.xml -您还可以创建一个servlet来处理其他servlet中的错误:-)请参阅 example here .

        2
  •  0
  •   D3X    11 年前

    我在一个网站上找到了下面的例子,认为这正是你的问题 http://www.journaldev.com/1973/servlet-exception-and-error-handling-example-tutorial

    Java代码:

     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错误处理:

    <?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>