DmitryBorodin
DmitryBorodin

Reputation: 4952

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).

Upvotes: 3

Views: 629

Answers (1)

wnc_21
wnc_21

Reputation: 1771

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

Upvotes: 1

Related Questions