gpt4 book ai didi

java - 如何在 Servlet 中使用 UncaughtExceptionHandler

转载 作者:搜寻专家 更新时间:2023-11-01 02:26:28 25 4
gpt4 key购买 nike

我在 tomcat 的启动上实现了一个 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.service() for servlet [ConnectGatewaysServlet] 在路径 [/infraview] 的上下文中抛出异常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?

最佳答案

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

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

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

关于java - 如何在 Servlet 中使用 UncaughtExceptionHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21747895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com