2

I've come across an issue in my application where I am checking for a specific error (lets say error 9000) in the onError of many different subscriptions. All of them may or may not handle the error in the same way. Rather than doing a check if(error == 9000) in the OnError of these subscriptions is there a way to create a custom Observable or operator that checks for this error specifically or maybe something like a .doOn9000Error()

1 Answer 1

6

You could write a simple function handleErr9000 which takes an Observable, and transforms it into one which correctly deals with error 9000. The onErrorResumeNext operator is what you need: It takes a function which gets the error which occurred, and can decide, depending on the kind of error, what Observable sequence to continue with.

public static <T> Observable<T> handleErr9000(Observable<T> o) { return o.onErrorResumeNext(new Func1<Throwable, Observable<T>>() { public Observable<T> call(Throwable err) { if (err instanceof NumberedException && ((NumberedException) err).number == 9000) { // Handle this specific error ... // Then return Observable.error(err) if you want to keep // the error, or Observable.just(someDefaultValue) to // substitute the error by a default value, // or Observable.empty() to swallow the error return Observable.empty(); } else { // just pass on the error if it's a different error return Observable.error(err); } } }); } 

[I invented an exception class named NumberedException for this example, you probably already have your own exception class for this.]

Sign up to request clarification or add additional context in comments.

1 Comment

That helped tremendously...thanks for the help, much appreciated

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.