如何处理 Spring 中已发布事件的异常

How to handle exceptions from a published event in Spring

我的应用程序使用 Spring 个事件

@Resource
ApplicationEventPublisher publisher;

publisher.publishEvent(myEvent);

...

@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void handleEvent(MyEvent myEvent)

有很多这样的事件。有没有办法处理来自这些订阅方法的潜在异常?

理想情况下,与在 Web MVC 中处理 RequestMapping 请求的异常的方式类似,即

@ExceptionHandler(Exception.class)

您可能会使用 ApplicationEventMulticaster in this scenario, specifically the SimpleApplicationEventMulticasterApplicationEventMulticaster 实际上只是 Publisher 的一个功能更强大的版本,它允许您执行诸如异步发布之类的操作。

但是,您在这里寻找的功能是 #setErrorHandler method on the Multicaster, where you can set a standard Spring ErrorHandler,或者(可能是您想要做的)在 ErrorHandler 界面上滚动您自己的功能。