如何在javaspring中处理全局异常



目前我正在开发一个小型系统,以记录所有未捕获的异常,并将其存储到数据库中,以便进一步调试/开发。为了做到这一点,我为特定线程使用了UnaughtException处理程序:

public class GlobalExceptionHandler implements Thread.UncaughtExceptionHandler{
@Autowired
private LoggedExceptionService service;

public GlobalExceptionHandler() {
}
@Override
public void uncaughtException(Thread t, Throwable e) {
System.err.println("IN UNCAUGHTEXCEPTION METHOD");
this.service.saveException(new LoggedException(e));
}
}

正如您所看到的,字段service被注入,当我捕捉到异常时,我会得到一个NullPointerException,因为该字段为null。

主要问题是GlobalExceptionHandler的使用。如果我使用构造函数注入(就像这个代码片段中那样(:

private LoggedExceptionService service;
@Autowired
public GlobalExceptionHandler(LoggedExceptionService service) {
this.service = service;
}

然后该字段不为null,但我不能将其声明为异常处理程序,因为我不能将它自动连接到java本机方法。电话是:

Thread.setDefaultUncaughtExceptionHandler(new GlobalExceptionHandler());

是否有可能将处理程序自动连接到线程方法,或者有什么好方法?

将其作为一个组件,并在@PostContruct方法中设置derault异常处理程序。

@Component
public class GlobalExceptionHandler implements Thread.UncaughtExceptionHandler{
@Autowired
private LoggedExceptionService service;

public GlobalExceptionHandler() {
}
@PostContruct
public void init(){
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
System.err.println("IN UNCAUGHTEXCEPTION METHOD");
this.service.saveException(new LoggedException(e));
}
}

这允许您自动设置处理程序,因为组件中用@PostContruct注释的方法在启动时会自动执行。

使GlobalExceptionHandler成为弹簧组件还允许对service进行自动布线,否则将永远不会进行设置。无论如何,我建议你使用美国的构造函数自动布线:

@Component
public class GlobalExceptionHandler implements Thread.UncaughtExceptionHandler{
private final LoggedExceptionService service;
@Autowired // @Autowired is actually not necessary if this is the only constructor
public GlobalExceptionHandler(LoggedExceptionService service) {
this.service=service
}
@PostContruct
public void init(){
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
System.err.println("IN UNCAUGHTEXCEPTION METHOD");
this.service.saveException(new LoggedException(e));
}
}

最新更新