在Spring Boot应用程序中没有调用Thread.setDefaultUncaughtExceptionHandler

时间:2016-02-22 21:25:36

标签: java spring maven spring-boot

我正在尝试在spring引导应用程序中实现一个全局未捕获的异常处理程序,它从一堆客户端应用程序中收集指标和异常等。看来我在调试时设置了处理程序,所以我假设在我的代码运行后分配了另一个处理程序,或者这些处理程序没有在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();
        }

}

我做错了什么?真的在这里敲我的头,任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:2)

因为您的 RuntimeException 被嵌入式tomcat捕获。您可以在 org.apache.catalina.core.StandardWrapperValve.invoke try catch >。 它打印完整的异常消息,并将错误放在响应中。

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