在google guava eventbus中显示异常

a64a0gku  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(522)

googleguavaeventbus接受异常并记录它们。
我编写了一个非常简单的应用程序来解释我的方法:

  1. public class SimplePrinterEvent {
  2. @Subscribe
  3. public void doPrint(String s) {
  4. int a = 2/0; //This is to fire an exception
  5. System.out.println("printing : " + s );
  6. }
  7. }

演示

  1. public class SimplePrinterEventDemo {
  2. public static void main(String[] args) {
  3. EventBus eventBus = new EventBus();
  4. eventBus.register(new SimplePrinterEvent());
  5. try{
  6. eventBus.post("This is going to print");
  7. }
  8. catch(Exception e){
  9. System.out.println("Error Occured!");
  10. }
  11. }
  12. }

这是永远不会到捕捉块!
所以我添加了一个subscriberexceptionhandler并重写了handleexception()。

  1. EventBus eventBus = new EventBus(new SubscriberExceptionHandler() {
  2. @Override
  3. public void handleException(Throwable exception,
  4. SubscriberExceptionContext context) {
  5. System.out.println("Handling Error..yes I can do something here..");
  6. throw new RuntimeException(exception);
  7. }
  8. });

它允许我在处理程序内部处理异常,但我的要求是将异常带到顶层,在顶层处理它们。
编辑:我在一些网站上找到的一个旧的解决方案(这与Guavav18有关)

  1. public class CustomEventBus extends EventBus {
  2. @Override
  3. void dispatch(Object event, EventSubscriber wrapper) {
  4. try {
  5. wrapper.handleEvent(event);
  6. } catch (InvocationTargetException cause) {
  7. Throwables.propagate(Throwables.getRootCause(cause));
  8. }
  9. }
  10. }
vsaztqbk

vsaztqbk1#

以下技巧对我很有效:
最新的eventbus类有一个名为 handleSubscriberException() 您需要在扩展的eventbus类中重写它:(这里我包括了两种解决方案,只有一种适用于您的版本)

  1. public class CustomEventBus extends EventBus {
  2. //If version 18 or bellow
  3. @Override
  4. void dispatch(Object event, EventSubscriber wrapper) {
  5. try {
  6. wrapper.handleEvent(event);
  7. } catch (InvocationTargetException cause) {
  8. Throwables.propagate(Throwables.getRootCause(cause));
  9. }
  10. }
  11. //If version 19
  12. @Override
  13. public void handleSubscriberException(Throwable e, SubscriberExceptionContext context) {
  14. Throwables.propagate(Throwables.getRootCause(e));
  15. }
  16. }
展开查看全部

相关问题