Difference between catch and onErrorResumeNext
They are distinct.
As you've noted, both operators handle failure similarly; however, they differ in their handling of completion.
OnErrorResumeNext
is simply a specialization with the following semantics:
"My query concatenates two observables. If the first observable fails, then resume with the next observable anyway."
Catch
is far more general:
"My query avoids failure. If the observable fails, then continue with another observable."
If you're avoiding failure on the boundary of concatenation, then use OnErrorResumeNext
; otherwise, to avoid failures in general use Catch
.
Related videos on Youtube
Vít Kotačka
Updated on June 04, 2022Comments
-
Vít Kotačka almost 2 years
In RxJS, there seems to be very little difference between an Observable instance's
catch
method andonErrorResumeNext
method, besides the fact thatonErrorResumeNext
concatenates the original Observable with the Observable parameters whether an error happens or not.If that's the case, isn't the naming a bit confusing? Because in case there is an error ,
onErrorResumeNext
works exactly the same way thancatch
does:var testObservable = Rx.Observable.return(1).concat(Rx.Observable.throw("Error")) // Both onError and onCatch will emit the same result: 1, 2 var onError = testObservable.onErrorResumeNext(Rx.Observable.return(2)); var onCatch = testObservable.catch(Rx.Observable.return(2));
Is there a strong reason for not always using
catch
? -
Brandon over 9 yearsThe name most likely comes from the Visual Basic
On Error Resume Next
statement, which has semantics similar to this operator. -
Vít Kotačka over 9 yearsYour reply makes sense, thanks. I guess that the confusion is about the naming because, as you point out, the main task of
onErrorResumeNext
is to concatenate, but this is not reflected at all in the name. -
Dave Sexton over 9 years@GiantSquid Well, I think concatenation is implied by the phrase "resume next", but I can see how that could be unclear at first.