2012-02-10 208 views

回答

8

因为它的立场,这是一个深思熟虑的决定,并在EventBus文档讨论:

处理程序不应该在一般情况下,抛出。如果他们这样做,EventBus将捕获并记录异常。这很少是错误处理的正确解决方案,不应该依赖;它的目的仅仅是为了帮助在开发过程中发现问题。

替代方案是being considered,虽然我很怀疑他们会使其进入12版

+0

你能解决这个问题吗? – 2012-02-10 21:41:04

+1

链接固定,现在就试试。 – 2012-02-10 22:40:24

4

这里是懒惰

public class Events 
{ 
    public static EventBus createWithExceptionDispatch() 
    { 
     final EventBus bus; 

     MySubscriberExceptionHandler exceptionHandler = new MySubscriberExceptionHandler(); 
     bus = new EventBus(exceptionHandler); 
     exceptionHandler.setBus(bus); 
     return bus; 
    } 

    private static class MySubscriberExceptionHandler implements SubscriberExceptionHandler 
    { 
     @Setter 
     EventBus bus; 

     @Override 
     public void handleException(Throwable exception, SubscriberExceptionContext context) 
     { 
      ExceptionEvent event = new ExceptionEvent(exception, context); 
      bus.post(event); 
     } 
    } 
} 

代码现在,您可以订阅ExceptionEvent

这是我ExceptionEvent只是复制粘贴&

@Data 
@Accessors(chain = true) 
public class ExceptionEvent 
{ 
    private final Throwable exception; 
    private final SubscriberExceptionContext context; 
    private final Object extra; 

    public ExceptionEvent(Throwable exception) 
    { 
     this(exception, null); 
    } 

    public ExceptionEvent(Throwable exception, Object extra) 
    { 
     this(exception,null,extra); 
    } 

    public ExceptionEvent(Throwable exception, SubscriberExceptionContext context) 
    { 
     this(exception,context,null); 
    } 

    public ExceptionEvent(Throwable exception, SubscriberExceptionContext context, Object extra) 
    { 
     this.exception = exception; 
     this.context = context; 
     this.extra = extra; 
    } 
} 
0

只是继承番石榴EventBus,写你自己的自定义eventbus。 提示:此类应写入com.google.common.eventbus包中,以便可以覆盖内部方法。

package com.google.common.eventbus; 

import com.google.common.util.concurrent.MoreExecutors; 

public class CustomEventBus extends EventBus { 

    /** 
    * Creates a new EventBus with the given {@code identifier}. 
    * 
    * @param identifier a brief name for this bus, for logging purposes. Should be a valid Java 
    *  identifier. 
    */ 
    public CustomEventBus(String identifier) { 
     super(
      identifier, 
      MoreExecutors.directExecutor(), 
      Dispatcher.perThreadDispatchQueue(), 
      LoggingHandler.INSTANCE); 
    } 

    /** 
    * Creates a new EventBus with the given {@link SubscriberExceptionHandler}. 
    * 
    * @param exceptionHandler Handler for subscriber exceptions. 
    * @since 16.0 
    */ 
    public CustomEventBus(SubscriberExceptionHandler exceptionHandler) { 
     super(
      "default", 
      MoreExecutors.directExecutor(), 
      Dispatcher.perThreadDispatchQueue(), 
      exceptionHandler); 
    } 

    @Override 
    void handleSubscriberException(Throwable e, SubscriberExceptionContext context) { 
     throw new EventHandleException(e); 
    } 
}