下面列出了怎么用io.reactivex.exceptions.UndeliverableException的API类实例代码及写法,或者点击链接到github查看源代码。
private void configureRxJavaErrorHandler() {
RxJavaPlugins.setErrorHandler(e -> {
if (e instanceof UndeliverableException) {
// As UndeliverableException is a wrapper, get the cause of it to get the "real" exception
e = e.getCause();
}
if (e instanceof InterruptedException) {
// fine, some blocking code was interrupted by a dispose call
return;
}
Log.e(TAG, "Undeliverable exception received, not sure what to do", e);
});
}
private void setUpRxPlugin() {
Scheduler asyncMainThreadScheduler = AndroidSchedulers.from(Looper.getMainLooper(), true);
RxAndroidPlugins.setInitMainThreadSchedulerHandler(schedulerCallable -> asyncMainThreadScheduler);
RxJavaPlugins.setErrorHandler(e -> {
if (e instanceof UndeliverableException) {
e = e.getCause();
}
if ((e instanceof IOException) || (e instanceof SocketException)) {
return;
}
if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) {
Timber.d("Error in app");
Thread.currentThread().getUncaughtExceptionHandler()
.uncaughtException(Thread.currentThread(),e);
}
if (e instanceof IllegalStateException) {
Timber.d("Error in RxJava");
Thread.currentThread().getUncaughtExceptionHandler()
.uncaughtException(Thread.currentThread(),e);
}
Timber.d(e);
});
}
@Test
public void testIssue27ConnectionErrorReportedToRxJavaPlugins() {
try (Database db = Database.nonBlocking()
.url("jdbc:driverdoesnotexist://doesnotexist:1527/notThere").build()) {
Plugins.reset();
db.select("select count(*) from person") //
.getAs(Long.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS / 5, TimeUnit.SECONDS) //
.assertNoValues() //
.assertNotTerminated() //
.cancel();
Throwable e = Plugins.getSingleError();
assertTrue(e instanceof UndeliverableException);
assertTrue(e.getMessage().toLowerCase().contains("no suitable driver"));
}
}
@Override
public void onCreate() {
super.onCreate();
rxBleClient = RxBleClient.create(this);
RxBleClient.updateLogOptions(new LogOptions.Builder()
.setLogLevel(LogConstants.INFO)
.setMacAddressLogSetting(LogConstants.MAC_ADDRESS_FULL)
.setUuidsLogSetting(LogConstants.UUIDS_FULL)
.setShouldLogAttributeValues(true)
.build()
);
RxJavaPlugins.setErrorHandler(throwable -> {
if (throwable instanceof UndeliverableException && throwable.getCause() instanceof BleException) {
Log.v("SampleApplication", "Suppressed UndeliverableException: " + throwable.toString());
return; // ignore BleExceptions as they were surely delivered at least once
}
// add other custom handlers if needed
throw new RuntimeException("Unexpected Throwable in RxJavaPlugins error handler", throwable);
});
}
@Test
public void testDoesNotTwoErrorsIfUpstreamDoesNotHonourCancellationImmediately() {
try {
List<Throwable> list = new CopyOnWriteArrayList<Throwable>();
RxJavaPlugins.setErrorHandler(Consumers.addTo(list));
Burst.items(1).error(new ThrowingException())//
.compose(Transformers. //
collectWhile( //
Callables.<List<Integer>>constant(Lists.<Integer>newArrayList()), ADD, //
BiPredicates.throwing())) //
.test() //
.assertNoValues() //
.assertError(ThrowingException.class);
assertEquals(1, list.size());
System.out.println(list.get(0));
assertTrue(list.get(0) instanceof UndeliverableException);
assertTrue(list.get(0).getCause() instanceof ThrowingException);
} finally {
RxJavaPlugins.reset();
}
}
@Test
public void testOnErrorThrowsException() throws Exception {
RuntimeException expected = new RuntimeException();
RxJavaPlugins.setErrorHandler(throwable -> {
assertThat(throwable, is(instanceOf(UndeliverableException.class)));
assertThat(throwable.getCause(), is(sameInstance(expected)));
complete();
});
FakeWriteStream writeStream = new FakeWriteStream(vertx);
Observer<Integer> observer = RxHelper.toObserver(writeStream).onError(throwable -> {
throw expected;
});
Observable.<Integer>error(new RuntimeException())
.observeOn(RxHelper.scheduler(vertx))
.subscribeOn(RxHelper.scheduler(vertx))
.subscribe(observer);
await();
assertFalse("Did not expect writeStream end method to be invoked", writeStream.endInvoked());
}
@Test
public void testOnWriteStreamEndThrowsException() throws Exception {
RuntimeException expected = new RuntimeException();
RxJavaPlugins.setErrorHandler(throwable -> {
assertThat(throwable, is(instanceOf(UndeliverableException.class)));
assertThat(throwable.getCause(), is(sameInstance(expected)));
complete();
});
FakeWriteStream writeStream = new FakeWriteStream(vertx);
Observer<Integer> observer = RxHelper.toObserver(writeStream).onWriteStreamEnd(() -> {
throw expected;
});
Observable.just(0)
.observeOn(RxHelper.scheduler(vertx))
.subscribeOn(RxHelper.scheduler(vertx))
.subscribe(observer);
await();
assertTrue("Expected writeStream end method to be invoked", writeStream.endInvoked());
}
@Test
public void testOnErrorThrowsException() throws Exception {
RuntimeException expected = new RuntimeException();
RxJavaPlugins.setErrorHandler(throwable -> {
assertThat(throwable, is(instanceOf(UndeliverableException.class)));
assertThat(throwable.getCause(), is(sameInstance(expected)));
complete();
});
FakeWriteStream writeStream = new FakeWriteStream(vertx);
Subscriber<Integer> subscriber = RxHelper.toSubscriber(writeStream).onError(throwable -> {
throw expected;
});
Flowable.<Integer>error(new RuntimeException())
.observeOn(RxHelper.scheduler(vertx))
.subscribeOn(RxHelper.scheduler(vertx))
.subscribe(subscriber);
await();
assertFalse("Did not expect writeStream end method to be invoked", writeStream.endInvoked());
}
@Test
public void testOnWriteStreamEndThrowsException() throws Exception {
RuntimeException expected = new RuntimeException();
RxJavaPlugins.setErrorHandler(throwable -> {
assertThat(throwable, is(instanceOf(UndeliverableException.class)));
assertThat(throwable.getCause(), is(sameInstance(expected)));
complete();
});
FakeWriteStream writeStream = new FakeWriteStream(vertx);
Subscriber<Integer> subscriber = RxHelper.toSubscriber(writeStream).onWriteStreamEnd(() -> {
throw expected;
});
Flowable.just(0)
.observeOn(RxHelper.scheduler(vertx))
.subscribeOn(RxHelper.scheduler(vertx))
.subscribe(subscriber);
await();
assertTrue("Expected writeStream end method to be invoked", writeStream.endInvoked());
}
@Test
public void testPoolFactoryWhenFailsThenRecovers() {
AtomicReference<Throwable> ex = new AtomicReference<>();
Consumer<? super Throwable> handler = RxJavaPlugins.getErrorHandler();
RxJavaPlugins.setErrorHandler(t -> ex.set(t));
try {
TestScheduler s = new TestScheduler();
AtomicInteger c = new AtomicInteger();
NonBlockingPool<Integer> pool = NonBlockingPool.factory(() -> {
if (c.getAndIncrement() == 0) {
throw new TestException();
} else {
return c.get();
}
}) //
.maxSize(1) //
.scheduler(s) //
.createRetryInterval(10, TimeUnit.SECONDS) //
.build();
TestObserver<Integer> ts = pool.member() //
.map(m -> m.value()) //
.test() //
.assertNotTerminated() //
.assertNoValues();
s.triggerActions();
assertTrue(ex.get() instanceof UndeliverableException);
assertTrue(((UndeliverableException) ex.get()).getCause() instanceof TestException);
s.advanceTimeBy(10, TimeUnit.SECONDS);
s.triggerActions();
ts.assertComplete();
ts.assertValue(2);
} finally {
RxJavaPlugins.setErrorHandler(handler);
}
}
public static void addErrorHandler(final String TAG) {
RxJavaPlugins.setErrorHandler(e -> {
if (e instanceof UndeliverableException) {
if (!e.getCause().toString().contains("OperationSuccess")) {
UserError.Log.e(TAG, "RxJavaError: " + e.getMessage());
}
} else {
UserError.Log.wtf(TAG, "RxJavaError2:" + e.getClass().getCanonicalName() + " " + e.getMessage() + " " + JoH.backTrace(3));
}
});
}
public static void addErrorHandler(final String TAG) {
RxJavaPlugins.setErrorHandler(e -> {
if (e instanceof UndeliverableException) {
if (!e.getCause().toString().contains("OperationSuccess")) {
UserError.Log.e(TAG, "RxJavaError: " + e.getMessage());
}
} else {
UserError.Log.wtf(TAG, "RxJavaError2:" + e.getClass().getCanonicalName() + " " + e.getMessage() + " " + JoH.backTrace(3));
}
});
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
Fabric.with(this, new Crashlytics());
// Fix the SSLHandshake error with okhttp on Android 4.1-4.4 when server only supports TLS1.2
// see https://github.com/square/okhttp/issues/2372 for more information
try {
ProviderInstaller.installIfNeeded(getApplicationContext());
} catch (Exception e) {
Timber.e(e, "Google Play ProviderInstaller exception");
}
// Init datetime
AndroidThreeTen.init(this);
// Timber
if (BuildConfig.DEBUG) Timber.plant(new Timber.DebugTree());
Timber.plant(new CrashlyticsTree());
// Prefs
Preferences.init(this);
Preferences.performHousekeeping();
// Image viewer
// Needs ARGB_8888 to be able to resize images using RenderScript
// (defaults to Bitmap.Config.RGB_565 if not set)
CustomSubsamplingScaleImageView.setPreferredBitmapConfig(Bitmap.Config.ARGB_8888);
// Init version number on first run
if (0 == Preferences.getLastKnownAppVersionCode())
Preferences.setLastKnownAppVersionCode(BuildConfig.VERSION_CODE);
// Firebase
boolean isAnalyticsEnabled = Preferences.isAnalyticsEnabled();
FirebaseAnalytics.getInstance(this).setAnalyticsCollectionEnabled(isAnalyticsEnabled);
// DB housekeeping
performDatabaseHousekeeping();
// Init notification channels
UpdateNotificationChannel.init(this);
DownloadNotificationChannel.init(this);
MaintenanceNotificationChannel.init(this);
// Clears all previous notifications
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null) manager.cancelAll();
// Run app update checks
if (Preferences.isAutomaticUpdateEnabled()) {
Intent intent = UpdateCheckService.makeIntent(this, false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
}
}
// Build Android shortcuts
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
ShortcutHelper.buildShortcuts(this);
}
// Send stats to Firebase
FirebaseAnalytics.getInstance(this).setUserProperty("color_theme", Integer.toString(Preferences.getColorTheme()));
FirebaseAnalytics.getInstance(this).setUserProperty("endless", Boolean.toString(Preferences.getEndlessScroll()));
// Plug the lifecycle listener to handle locking
ProcessLifecycleOwner.get().getLifecycle().addObserver(new LifeCycleListener());
// Set RxJava's default error handler for unprocessed network and IO errors
RxJavaPlugins.setErrorHandler(e -> {
if (e instanceof UndeliverableException) {
e = e.getCause();
}
if (e instanceof IOException) {
// fine, irrelevant network problem or API that throws on cancellation
return;
}
if (e instanceof InterruptedException) {
// fine, some blocking code was interrupted by a dispose call
return;
}
Timber.w(e, "Undeliverable exception received, not sure what to do");
});
}