Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rx-Java centralized error handling

I use Retrofit as network library with Rx-Java. I want to make some centralized error checking for most requests and handle errors or pass it to subscriber's onError() if I cannot handle it. How could I do this?

Something like this

 projectListObservable
    .subscribeOn(Schedulers.newThread())
    .timeout(App.NETWORK_TIMEOUT_SEC, TimeUnit.SECONDS)
    .retry(App.NETWORK_RETRY_COUNT)
    .onError(e -> {
     if (e instanseOf HttpError && ((HttpError)e).getCode == 403){
        App.getInstance.getNetworkManager.reAuth();
     } else {
        throw(e);
     }})
   .observeOn(AndroidSchedulers.mainThread())
   .subscribe(new ProjectListSubscriber());

Also, I should stop retrying in that case, but keep retry if it's a network problem (instanceof IOException).

like image 686
DmitryBorodin Avatar asked May 30 '26 16:05

DmitryBorodin


1 Answers

I think you want to implement too many tihngs with a single observable.

You can have some HttpErrorHandler which will have method

boolean fix(Exception e) 

if error handler fixed the exception(renew token etc) return true. You can have differrent error handlers for different cases or one for everything. TokenErrorHandler RetryErrorHandler and then make a chain.

If all error hadlers return false, throw this exception to the up level

like image 138
wnc_21 Avatar answered Jun 01 '26 05:06

wnc_21



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!