【问题标题】:How to use an UncaughtExceptionHandler in Servlets如何在 Servlet 中使用 UncaughtExceptionHandler
【发布时间】:2014-02-13 07:35:00
【问题描述】:

我在tomcat的StartUp上实现了一个UncaughtExceptionHandler:

 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:servlet [ConnectGatewaysServlet] 在路径 [/infraview] 的上下文中的 Servlet.service() 引发异常 java.lang.ArithmeticException: / 由零 在 net.test.gateway.ConnectGatewaysServlet.doPost(ConnectGatewaysServlet.java:73) 在 javax.servlet.http.HttpServlet.service(HttpServlet.java:647) 在 javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

如何为 Servlet 实现 UncaughtExceptionHandler?

【问题讨论】:

    标签: java exception uncaughtexceptionhandler


    【解决方案1】:

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

    您可以做的是将doPost() 的内容包装在try-catch 块中。

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

    【讨论】:

    • 第一个说法不正确。由于StandardWrapperValve 处理了异常,因此未调用处理程序。例外不再没有被发现。与您所写的相反,Thread#setDefaultUncaughtExceptionHandler() 确实为所有线程设置了一个处理程序,其中:没有使用Thread#setUncaughtExceptionHandler() 注册自己的处理程序并且没有覆盖ThreadGroupThreadGroup 实现@。
    • 嗨,Eduard,哇,多么古老的话题 :D 无论如何,感谢您的澄清,你说得对。
    • 我知道这确实很旧,但我发现它正在寻找解决方案。由于您的答案已被接受,您能否使用来自@EduardWirch 的正确信息对其进行更新?
    【解决方案2】:

    我在一个网站上找到了以下示例,认为这正是您的问题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>
    

    【讨论】:

    • 你基本上是复制并粘贴了我链接的教程中的代码 :-))
    • 对不起,我没注意到,有人已经放了链接:(反正目的是学习。
    猜你喜欢
    • 2014-06-01
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 2015-03-13
    相关资源
    最近更新 更多