私は guava の EventBus を使用していますが、残念ながら、イベント ハンドラーが RuntimeException をスローしたときに発生する InvocationTargetException をキャッチしてログに記録します。この動作を無効にすることはできますか?
3070 次
3 に答える
8
現状では、これは意図的な決定であり、EventBus ドキュメントで説明されています。
一般に、ハンドラーはスローすべきではありません。その場合、EventBus は例外をキャッチしてログに記録します。これがエラー処理の適切な解決策になることはめったになく、依存すべきではありません。開発中の問題の発見を支援することのみを目的としています。
代替ソリューションが検討されていますが、それらがリリース 12 に組み込まれるかどうかは真剣に疑っています。
于 2012-02-10T20:00:18.920 に答える
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;
}
}
于 2014-10-30T02:28:37.670 に答える
0
guava 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);
}
}
于 2016-11-29T03:24:30.757 に答える