diff --git a/src/main/java/com/box/sdk/EventListener.java b/src/main/java/com/box/sdk/EventListener.java index 30db92bbc..edd862e93 100644 --- a/src/main/java/com/box/sdk/EventListener.java +++ b/src/main/java/com/box/sdk/EventListener.java @@ -2,4 +2,6 @@ public interface EventListener { void onEvent(BoxEvent event); + + boolean onException(Throwable e); } diff --git a/src/main/java/com/box/sdk/EventStream.java b/src/main/java/com/box/sdk/EventStream.java index ed2493df5..ce13c5ab4 100644 --- a/src/main/java/com/box/sdk/EventStream.java +++ b/src/main/java/com/box/sdk/EventStream.java @@ -54,7 +54,13 @@ public void start() { final long initialPosition = jsonObject.get("next_stream_position").asLong(); this.poller = new Poller(initialPosition); - new Thread(this.poller).start(); + Thread pollerThread = new Thread(this.poller); + pollerThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { + public void uncaughtException(Thread t, Throwable e) { + EventStream.this.notifyException(e); + } + }); + pollerThread.start(); this.started = true; } @@ -74,6 +80,17 @@ private void notifyListeners(BoxEvent event) { } } + private void notifyException(Throwable e) { + this.stop(); + synchronized (this.listenerLock) { + for (EventListener listener : this.listeners) { + if (listener.onException(e)) { + return; + } + } + } + } + private class Poller implements Runnable { private final long initialPosition; private final Object setServerLock; diff --git a/src/test/java/com/box/sdk/EventStreamTest.java b/src/test/java/com/box/sdk/EventStreamTest.java index c95b21e57..a001e17e0 100644 --- a/src/test/java/com/box/sdk/EventStreamTest.java +++ b/src/test/java/com/box/sdk/EventStreamTest.java @@ -21,6 +21,10 @@ public void receiveEventsForFolderCreateAndFolderDelete() throws InterruptedExce public void onEvent(BoxEvent event) { observedEvents.add(event); } + + public boolean onException(Throwable e) { + return true; + } }); stream.start();