[英]Java - listen when an exception is caught in an external class
Is there a way to create a listener in a separate class that runs a certain piece of code whenever an exception is caught within your project? 有没有一种方法可以在单独的类中创建侦听器,该类在项目中捕获异常时运行特定代码?
My code has a lot of try-catches in it, and if an exception is caught I would like to see the logs using log4j. 我的代码中有很多尝试,如果捕获到异常,我希望使用log4j查看日志。 I can do the following for every try-catch I have fairly easily (just with some time effort):
我可以很轻松地为每次尝试捕获执行以下操作(只需花费一些时间):
private static final Logger logger = LogManager.getLogger(Example.class);
public void testMethod() {
try {
// some code here that could throw an exception
} catch(Exception e) {
logger.error("Unexpected error has occurred: ", e);
}
}
This will log the exception using log4j. 这将使用log4j记录异常。 However, I would need to do that over 50 times, and it's so redundant that I would rather be able to use 1 method to do that.
但是,我需要这样做超过50次,而且它是如此冗余,以至于我宁愿能够使用1种方法来做到这一点。 So, is there a way to instead do something like this?
那么,有没有办法做这样的事情?
public class ListenerClass {
private static final Logger logger = LogManager.getLogger(ListenerClass.class);
// This method will be listening for exceptions to be caught within the project
/**
* @param e - The exception that was just caught
*/
public void listenerMethod(ExceptionCaught e) {
logger.error("An exception has been thrown: ", e);
}
}
Is this possible? 这可能吗?
Thanks 谢谢
Thread.setDefaultUncaughtExceptionHandler( (thread, throwable) -> {
log(throwable.getMessage(), thread.getId());
});
which will handle uncaught RuntimeException
s, and unless otherwise specified it will act for all your application threads. 它将处理未捕获的
RuntimeException
,除非另有说明,否则它将对所有应用程序线程起作用。
Just remember the Exceptions are thrown for a reason, and shouldn't be ignored, especially RuntimeException
s. 请记住,抛出Exception是有原因的,因此不应忽略,尤其是
RuntimeException
。
If you are using an older version of java
(before 8), you must explicitly instantiate an anonymous class: 如果您使用的是
java
的旧版本(8之前的版本),则必须显式实例化一个匿名类:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(final Thread t, final Throwable e) {
}
});
看Thread.setDefaultUncaughtExceptionHandler()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.