Skip to content

Commit 77fb254

Browse files
committed
Allow EventListeners to handle exceptions
Any uncaught exceptions on the EventStream's polling thread will be sent to the EventStream listeners through the onException(Throwable e) method. The exception will be sent to each listener (in the order in which they were added) until one of them returns true, indicating that the exception was handled.
1 parent 9496aba commit 77fb254

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

src/main/java/com/box/sdk/EventListener.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,6 @@
22

33
public interface EventListener {
44
void onEvent(BoxEvent event);
5+
6+
boolean onException(Throwable e);
57
}

src/main/java/com/box/sdk/EventStream.java

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,13 @@ public void start() {
5454
final long initialPosition = jsonObject.get("next_stream_position").asLong();
5555
this.poller = new Poller(initialPosition);
5656

57-
new Thread(this.poller).start();
57+
Thread pollerThread = new Thread(this.poller);
58+
pollerThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
59+
public void uncaughtException(Thread t, Throwable e) {
60+
EventStream.this.notifyException(e);
61+
}
62+
});
63+
pollerThread.start();
5864

5965
this.started = true;
6066
}
@@ -74,6 +80,17 @@ private void notifyListeners(BoxEvent event) {
7480
}
7581
}
7682

83+
private void notifyException(Throwable e) {
84+
this.stop();
85+
synchronized (this.listenerLock) {
86+
for (EventListener listener : this.listeners) {
87+
if (listener.onException(e)) {
88+
return;
89+
}
90+
}
91+
}
92+
}
93+
7794
private class Poller implements Runnable {
7895
private final long initialPosition;
7996
private final Object setServerLock;

src/test/java/com/box/sdk/EventStreamTest.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ public void receiveEventsForFolderCreateAndFolderDelete() throws InterruptedExce
2121
public void onEvent(BoxEvent event) {
2222
observedEvents.add(event);
2323
}
24+
25+
public boolean onException(Throwable e) {
26+
return true;
27+
}
2428
});
2529
stream.start();
2630

0 commit comments

Comments
 (0)