Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS "throw new Error" vs "Observable.throw"

Tags:

Is there a difference between throw new Error() and Observable.throw() and if so what is it? Obviously since Observable.throw exists there is some reason for it, but besides a shorter stack trace I could not find any differences.

Here's an example

like image 962
blaugold Avatar asked Jul 01 '17 18:07

blaugold


1 Answers

Observable.throw returns an error when in streams. For example I am expecting an Observable but for some reason, I want to return an error. These cases its not possible to use throw new Error() .

For example:

var source = someStream$
    .flatMap(data => data?
             Rx.Observable.of(data): // Or any other async operation 
             Rx.Observable.throw('invalid data'));

Here flatMap expects an Observable stream, if we need to use throw new Error() we need to do a hack .

It might have other advantages also to work well with the rx operators,that I am not aware of .

like image 142
Vamshi Avatar answered Oct 11 '22 13:10

Vamshi