I am using Guava EventBus in sync. How can I rollback the complete transaction if any of the subscribers throw an Exception? How can I throw an Exception which will not be caught by the EventBus Subscriber?
I solved it using java.lang.ThreadLocal
variable across the publisher and the subscriber.
Publisher needs to be wrapped in a class which reads thread local exception and throws it
public void publish(Event event) {
eventBus.post(event);
if(threadLocalException != null) {
Store threadLocalException in some variable say e
Clear threadLocalException variable
throw e;
}
}
Subscriber needs to be wrapped in a class to set the exception in thread local variable
public abstract class EventSubscriber<T extends Event> {
@Subscribe
public void invoke(T event) {
try {
handle(event);
} catch (Exception e) {
Set thread local variable to e
}
}
protected abstract void handle(T event);
}