【问题标题】:Thread.setDefaultUncaughtExceptionHandler not being called in Spring Boot application未在 Spring Boot 应用程序中调用 Thread.setDefaultUncaughtExceptionHandler
【发布时间】:2016-02-22 21:25:35
【问题描述】:

我正在尝试在 Spring Boot 应用程序中实现一个全局未捕获异常处理程序,该处理程序从一堆客户端应用程序中收集指标和异常等。似乎在我调试时正在设置处理程序,所以我假设在我的代码运行后分配了另一个处理程序,或者这些处理程序没有在 spring 应用程序上下文中设置?我的代码如下。

我已经为我的默认异常处理程序创建了这个类 -

public class JvmrtExceptionHandler implements Thread.UncaughtExceptionHandler {

private static final Logger LOGGER = LoggerFactory.getLogger(JvmrtExceptionHandler.class);
private RestTemplate restTemplate = new RestTemplate();

@Override
public void uncaughtException(Thread thread, Throwable exception) {
    String exceptionClass = exception.getStackTrace()[0].getClassName();
    String exceptionMethod = exception.getStackTrace()[0].getMethodName();
    String exceptionMessage = exception.getMessage();
    String exceptionType = exception.getClass().getSimpleName();
    String appName = exception.getClass().getPackage().getImplementationTitle();
    ExceptionModel thrownException = new ExceptionModel(
            exceptionMessage,
            appName,
            exceptionMethod,
            exceptionClass,
            exceptionType
    );

    LOGGER.error("Uncaught Exception thrown of type {}. Sending to JVMRT Main app for processing", exceptionType);

    String exceptionUrl = String.format("http://%s:%s/api/", "localhost", 8090);
    restTemplate.postForObject(exceptionUrl, thrownException, String.class);



}

}

这个类,在另一个应用程序中,将前一个应用程序作为 maven 依赖项,配置我创建的默认处理程序。我希望处理程序适用于所有线程,因此我使用了静态 Thread.setDefaultUncaughtExceptionHandler 方法来设置它。

@Configuration
public class Config {

    @Bean
    public JvmrtExceptionHandler jvmrtExceptionHandler() {
        JvmrtExceptionHandler exceptionHandler = new JvmrtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);
        return exceptionHandler;
    }
}

我正在使用以下代码测试处理程序。

@RestController
@RequestMapping(value = "/test")
public class ExceptionTest {

        @RequestMapping(value = "/exception", method = RequestMethod.GET)
        public void throwException() {
           throw new RuntimeException();
        }

}

我做错了什么?真的在这里敲我的头,任何帮助将不胜感激。

【问题讨论】:

    标签: java spring maven spring-boot


    【解决方案1】:

    因为你的RuntimeException被embed tomcat捕获了。你可以在org.apache.catalina.core.StandardWrapperValve.invoke中找到try catch >。 它打印完整的异常消息,并在响应中输入错误。

    如果你想在 spring 请求映射中捕获异常。你可以尝试 ControllerAdviceExceptionHandler

    【讨论】:

    • 让它与 ExceptionHandler 一起工作。感谢您的帮助。
    • 我使用ControllerAdvice发现@Async中的异常不会被捕获。你知道怎么处理这个案子吗?
    猜你喜欢
    • 2020-01-12
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 2022-11-11
    • 2019-08-07
    • 2019-05-16
    相关资源
    最近更新 更多