Java Code Examples for io.reactivex.plugins.RxJavaPlugins#setErrorHandler()
The following examples show how to use
io.reactivex.plugins.RxJavaPlugins#setErrorHandler() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CompletableThrowingTest.java From retrocache with Apache License 2.0 | 6 votes |
@Test public void throwingInOnCompleteDeliveredToPlugin() { server.enqueue(new MockResponse()); final AtomicReference<Throwable> errorRef = new AtomicReference<>(); RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { if (!errorRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); // Don't swallow secondary errors! } } }); RecordingCompletableObserver observer = observerRule.create(); final RuntimeException e = new RuntimeException(); service.completable().subscribe(new ForwardingCompletableObserver(observer) { @Override public void onComplete() { throw e; } }); assertThat(errorRef.get()).isSameAs(e); }
Example 2
Source File: MaybeThrowingTest.java From retrocache with Apache License 2.0 | 6 votes |
@Test public void resultThrowingInOnSuccessDeliveredToPlugin() { server.enqueue(new MockResponse()); final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { if (!throwableRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); } } }); RecordingMaybeObserver<Result<String>> observer = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service.result().subscribe(new ForwardingObserver<Result<String>>(observer) { @Override public void onSuccess(Result<String> value) { throw e; } }); assertThat(throwableRef.get()).isSameAs(e); }
Example 3
Source File: StringsSplitTest.java From rxjava2-extras with Apache License 2.0 | 6 votes |
@Test @Ignore public void testSplitSimpleNormalCancelledAtBegginning() { try { List<Throwable> list = new CopyOnWriteArrayList<Throwable>(); RxJavaPlugins.setErrorHandler(Consumers.addTo(list)); Flowable.just("boo:an", "d:you") // .compose(Strings.splitSimple(":")) // .test(-5) // .assertNoValues() // .assertNotTerminated(); assertEquals(1, list.size()); assertTrue(list.get(0) instanceof IllegalArgumentException); } finally { RxJavaPlugins.reset(); } }
Example 4
Source File: AdamantApplication.java From adamant-android with GNU General Public License v3.0 | 6 votes |
@Override public void onCreate() { super.onCreate(); RxJavaPlugins.setErrorHandler(e -> LoggerHelper.e("UNCAUGHT RX", e.getMessage(), e)); DaggerAppComponent .builder() .context(this) .build() .inject(this); LocaleChanger.initialize(getApplicationContext(), supportedLocales); // if (LeakCanary.isInAnalyzerProcess(this)) { // // This process is dedicated to LeakCanary for heap analysis. // // You should not init your app in this process. // return; // } // // LeakCanary.install(this); }
Example 5
Source File: App.java From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License | 6 votes |
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); }); }
Example 6
Source File: WriteStreamObserverTest.java From vertx-rx with Apache License 2.0 | 6 votes |
@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()); }
Example 7
Source File: CommonApplicationLike.java From AcgClub with MIT License | 5 votes |
/** * RxJava2 当取消订阅后(dispose()),RxJava抛出的异常后续无法接收(此时后台线程仍在跑,可能会抛出IO等异常),全部由RxJavaPlugin接收,需要提前设置ErrorHandler * 详情:http://engineering.rallyhealth.com/mobile/rxjava/reactive/2017/03/15/migrating-to-rxjava-2.html#Error * Handling */ private void setRxJavaErrorHandler() { RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { LogUtil.d("setRxJavaErrorHandler:"); throwable.printStackTrace(); } }); }
Example 8
Source File: ObservableThrowingTest.java From retrocache with Apache License 2.0 | 5 votes |
@Test public void bodyThrowingInOnCompleteDeliveredToPlugin() { server.enqueue(new MockResponse()); final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { if (!throwableRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); } } }); RecordingObserver<String> observer = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service.body().subscribe(new ForwardingObserver<String>(observer) { @Override public void onComplete() { throw e; } }); observer.assertAnyValue(); assertThat(throwableRef.get()).isSameAs(e); }
Example 9
Source File: AsyncTest.java From retrocache with Apache License 2.0 | 5 votes |
@Test public void throwingInOnCompleteDeliveredToPlugin() throws InterruptedException { server.enqueue(new MockResponse()); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> errorRef = new AtomicReference<>(); RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { if (!errorRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); // Don't swallow secondary errors! } latch.countDown(); } }); TestObserver<Void> observer = new TestObserver<>(); final RuntimeException e = new RuntimeException(); service.completable().subscribe(new ForwardingCompletableObserver(observer) { @Override public void onComplete() { throw e; } }); latch.await(1, SECONDS); assertThat(errorRef.get()).isSameAs(e); }
Example 10
Source File: Subscription.java From xDrip with GNU General Public License v3.0 | 5 votes |
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)); } }); }
Example 11
Source File: Subscription.java From xDrip-plus with GNU General Public License v3.0 | 5 votes |
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)); } }); }
Example 12
Source File: UnhandledRxJavaErrorRule.java From reactive-grpc with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override protected void after() { RxJavaPlugins.setErrorHandler(null); if (autoverify) { verifyNoError(); } }
Example 13
Source File: FlowableThrowingTest.java From retrocache with Apache License 2.0 | 5 votes |
@Test public void bodyThrowingInOnCompleteDeliveredToPlugin() { server.enqueue(new MockResponse()); final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { if (!throwableRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); } } }); RecordingSubscriber<String> subscriber = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service.body().subscribe(new ForwardingSubscriber<String>(subscriber) { @Override public void onComplete() { throw e; } }); subscriber.assertAnyValue(); assertThat(throwableRef.get()).isSameAs(e); }
Example 14
Source File: AbstractSubscriberAndProducerTest.java From reactive-grpc with BSD 3-Clause "New" or "Revised" License | 5 votes |
@BeforeEach public void setUp() { RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() { @Override public void accept(Throwable throwable) { unhandledThrowable.offer(throwable); } }); }
Example 15
Source File: RxJavaHooksUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void givenObservable_whenError_shouldExecuteTheHook() { RxJavaPlugins.setErrorHandler(throwable -> { hookCalled = true; }); Observable.error(new IllegalStateException()) .subscribe(); assertTrue(hookCalled); }
Example 16
Source File: MainActivity.java From Reactive-Android-Programming with MIT License | 4 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); log(this.toString()); RxJavaPlugins.setErrorHandler(ErrorHandler.get()); ButterKnife.bind(this); recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); stockDataAdapter = new StockDataAdapter(); recyclerView.setAdapter(stockDataAdapter); Observable.just("Please use this app responsibly!") .subscribe(s -> helloText.setText(s)); YahooService yahooService = new RetrofitYahooServiceFactory().create(); String query = "select * from yahoo.finance.quote where symbol in ('YHOO','AAPL','GOOG','MSFT')"; String env = "store://datatables.org/alltableswithkeys"; Observable.interval(0, 5, TimeUnit.SECONDS) .compose(bindToLifecycle()) .flatMap( i -> yahooService.yqlQuery(query, env) .toObservable() ) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnError(error -> { Toast.makeText(this, "We couldn't reach internet - falling back to local data", Toast.LENGTH_SHORT) .show(); }) .observeOn(Schedulers.io()) .map(r -> r.getQuery().getResults().getQuote()) .flatMap(Observable::fromIterable) .map(StockUpdate::create) .doOnNext(this::saveStockUpdate) .onExceptionResumeNext( v2(StorIOFactory.get(this) .get() .listOfObjects(StockUpdate.class) .withQuery(Query.builder() .table(StockUpdateTable.TABLE) .orderBy("date DESC") .limit(50) .build()) .prepare() .asRxObservable()) .take(1) .flatMap(Observable::fromIterable) ) .observeOn(AndroidSchedulers.mainThread()) .subscribe(stockUpdate -> { Log.d("APP", "New update " + stockUpdate.getStockSymbol()); noDataAvailableView.setVisibility(View.GONE); stockDataAdapter.add(stockUpdate); }, error -> { if (stockDataAdapter.getItemCount() == 0) { noDataAvailableView.setVisibility(View.VISIBLE); } }); demo01(); }
Example 17
Source File: TestHelper.java From RxShell with Apache License 2.0 | 4 votes |
public static List<Throwable> trackPluginErrors() { final List<Throwable> list = Collections.synchronizedList(new ArrayList<Throwable>()); RxJavaPlugins.setErrorHandler(list::add); return list; }
Example 18
Source File: TestHelper.java From RxShell with Apache License 2.0 | 4 votes |
public static List<Throwable> trackPluginErrors() { final List<Throwable> list = Collections.synchronizedList(new ArrayList<Throwable>()); RxJavaPlugins.setErrorHandler(list::add); return list; }
Example 19
Source File: LingjuAudioPlayer.java From AssistantBySDK with Apache License 2.0 | 4 votes |
private LingjuAudioPlayer(Context context) { this.mContext = context; this.repository = AudioRepository.create(context); localMusicContentObserver = new LocalMusicContentObserver(new Handler(Looper.getMainLooper())); mContext.getContentResolver().registerContentObserver(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, false, localMusicContentObserver); boolean allow3g = AppConfig.dPreferences.getBoolean(AppConfig.DOWNLOAD_ON_WIFI, false); noOnlinePlayInMobileNet = !allow3g; /** * 使用Observable.subscribe()时,RxJava默认提供一个出错时消费者,然而该消费者默认为空(无语); * 需要开发者自行赋值。 * **/ RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { throwable.printStackTrace(); if (throwable instanceof FetchUrlException) { Log.i("LingJu", "ErrorHandler>>>" + ((FetchUrlException) throwable).getCode()); String text = null; SpeechMsgBuilder builder = SpeechMsgBuilder.create(text); switch (((FetchUrlException) throwable).getCode()) { case IBatchPlayer.Error.FETCH_OFFLINE_FAILED: text = mContext.getResources().getString(R.string.no_play_network_none); break; case IBatchPlayer.Error.FETCH_ON_2G_NETWORK: text = mContext.getResources().getString(R.string.no_play_network_2g); break; case IBatchPlayer.Error.FETCH_ON_34G_NETWORK: Intent intent = new Intent(mContext, AssistantService.class); intent.putExtra(AssistantService.CMD, AssistantService.ServiceCmd.PUSH_ROUTE_CACULATE); intent.putExtra(AssistantService.TEXT, PLAY_UNDER3G_HISTORY); mContext.startService(intent); text = Setting.CONFIRM_PLAY_UNDER_3G; builder.setContextMode(SpeechMsg.CONTEXT_KEEP_RECOGNIZE); break; case IBatchPlayer.Error.FETCHED_FAILED: break; } if (TextUtils.isEmpty(text)) return; //添加回复文本 EventBus.getDefault().post(new ChatMsgEvent(new ResponseMsg(text), null, null, null)); //合成声音 SynthesizerBase.get().startSpeakAbsolute(builder.setText(text).build()) .doOnNext(new Consumer<SpeechMsg>() { @Override public void accept(SpeechMsg speechMsg) throws Exception { if (speechMsg.state() == SpeechMsg.State.OnBegin) { EventBus.getDefault().post(new SynthesizeEvent(SynthesizeEvent.SYNTH_START)); } } }) .doOnComplete(new Action() { @Override public void run() throws Exception { EventBus.getDefault().post(new SynthesizeEvent(SynthesizeEvent.SYNTH_END)); } }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.computation()) .subscribe(); } } }); }
Example 20
Source File: MainActivity.java From Reactive-Android-Programming with MIT License | 4 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RxJavaPlugins.setErrorHandler(ErrorHandler.get()); ButterKnife.bind(this); recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); stockDataAdapter = new StockDataAdapter(); recyclerView.setAdapter(stockDataAdapter); Observable.just("Please use this app responsibly!") .subscribe(s -> helloText.setText(s)); YahooService yahooService = new RetrofitYahooServiceFactory().create(); String query = "select * from yahoo.finance.quote where symbol in ('YHOO','AAPL','GOOG','MSFT')"; String env = "store://datatables.org/alltableswithkeys"; Observable.interval(0, 5, TimeUnit.SECONDS) .flatMap( i -> Observable.<YahooStockResult>error(new RuntimeException("Crash")) ) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnError(error -> { log("doOnError", "error"); Toast.makeText(this, "We couldn't reach internet - falling back to local data", Toast.LENGTH_SHORT) .show(); }) .observeOn(Schedulers.io()) .map(r -> r.getQuery().getResults().getQuote()) .flatMap(Observable::fromIterable) .map(StockUpdate::create) .doOnNext(this::saveStockUpdate) .onExceptionResumeNext( v2(StorIOFactory.get(this) .get() .listOfObjects(StockUpdate.class) .withQuery(Query.builder() .table(StockUpdateTable.TABLE) .orderBy("date DESC") .limit(50) .build()) .prepare() .asRxObservable()) .take(1) .flatMap(Observable::fromIterable) ) .observeOn(AndroidSchedulers.mainThread()) .subscribe(stockUpdate -> { Log.d("APP", "New update " + stockUpdate.getStockSymbol()); noDataAvailableView.setVisibility(View.GONE); stockDataAdapter.add(stockUpdate); }, error -> { if (stockDataAdapter.getItemCount() == 0) { noDataAvailableView.setVisibility(View.VISIBLE); } }); // demo10(); }