简体   繁体   English

RxJS - 为什么我要使用 throwError 而不是简单地抛出错误?

[英]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.首先我想说清楚我知道Rx throwError 操作符和JS 的throw 关键字的区别。 I just wanted to know why would I use the throwError operator?我只是想知道为什么要使用 throwError 运算符? What am I gaining by creating a new observable that all it does is to throw an error the second anyone subscribes to it?通过创建一个新的 observable 我得到了什么,它所做的只是在任何人订阅它时抛出一个错误?

Long story short, why would I want to do this:长话短说,我为什么要这样做:

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

Over this:在这个:

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

Thanks!谢谢!

In this case, the syntax is the only difference.在这种情况下,语法是唯一的区别。 There is no reason to use throw instead of throwError or the other way around.没有理由使用throw而不是throwError或其他方式。 Choose one approach with your team and stick to it.与您的团队一起选择一种方法并坚持下去。

Proof证明

// Error using reactive throwError
// logs error 'oops!!'
of(1)
    .pipe(
        switchMap(
           (x) => throwError('oops!!'))
        )
    .subscribe({
        next: console.log,  // not called
        error: console.error, 
        complete: () => console.log('complete!'),  // not called
    }); 

// Error using imperative throw
// logs error 'oops!!'
of(1)
    .pipe(
        switchMap((x) => {
            throw 'oops!!';
        })
    )
    .subscribe({
        next: console.log,  // not called
        error: console.error,
        complete: () => console.log('complete!'), // not called
    }); 

The output is the same in both ways.两种方式的输出是相同的。 Note the completion handler which is not called in both scenarios, according to the Observable contract .请注意根据Observable 合同,在两种情况下都未调用的完成处理程序。

May be problematic to use throwError inside pipe operator as throwError observable may be just passed down the pipe depending on subsequent operations.在管道运算符中使用 throwError 可能有问题,因为 throwError observable 可能会根据后续操作沿管道向下传递。 See this article for details: https://medium.com/angular-in-depth/throwerror-is-not-throw-error-ad6c76c53377详情见这篇文章: https : //medium.com/angular-in-depth/throwerror-is-not-throw-error-ad6c76c53377

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 ,它将返回一个新的 observable 将发出该错误,本质上会将其传递到管道中。 throwError(error) is equivalent to this: throwError(error)相当于:

return new Observable(observer=>{
      observer.error(error)
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM