Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS - Why would I want to use throwError and not simply throw an error?

First of all, I want to make it clear that I know the difference between Rx throwError operator and JS's throw keyword. I just wanted to know why would I use the throwError operator? What am I gaining by creating a new observable that all it does is to throw an error the second anyone subscribes to it?

Long story short, why would I want to do this:

.catchError(err => throw "error!!")

Over this:

.catchError(err => throwError("error!!"))

Thanks!

like image 367
RiskX Avatar asked Nov 24 '18 16:11

RiskX


1 Answers

If you just throw an error, it will end the pipeline. If you use throwError, it will return a new observable that is going to emit that error, essentially will pass it on down the pipeline. throwError(error) is equivalent to this:

return new Observable(observer=>{
      observer.error(error)
    })
like image 61
Yilmaz Avatar answered Oct 05 '22 18:10

Yilmaz