【发布时间】: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