在 RxJS 中,错误回调与 .catch() 有什么区别?

In RxJS what's the difference between error callback vs .catch()?

如果我有如下代码:

const d: any = {};

return this.http.post(url, body, httpOptions).map(data => {
  return d;
}, error => {
  console.error('error');
})
.catch((err, d$) => {
  return Observable.of(d);
});

如果有任何类型的错误,即 POST 请求失败或 .map() 成功回调中的某些错误或任何其他类型的错误。

.map().catch() 回调中的错误回调将调用两个错误处理程序中的哪一个?它取决于可能发生的错误类型吗?

是否会因为 .catch() 运算符的存在而总是跳过 .map() 上的错误回调?

在您的示例中,如果发生错误,将调用 catch。此外,map 运算符没有第二个参数,因此永远不会调用该函数。如果您在订阅上有一个错误处理程序,那么在发生未处理的异常时将调用回调。 catchError 运算符是一种处理错误的方法。它基本上充当 switchMap 切换到新的可观察流。

示例:

订阅错误处理程序(Demo

return throwError('This is an error!').subscribe(data => {
  console.log("Got Data: ", data);
}, error => {
  console.error('error', error); // Observable stream has error so this prints
});

捕获错误 (Demo)

return throwError('This is an error!').pipe(
  catchError(error => {
    console.log("Error Caught", error);
    return of(2); // Catches the error and continues the stream with a value of 2
  }),
).subscribe(data => {
  console.log("Got Data: ", data); // Data will be logged
}, error => {
  console.error('error', error); // Will not be called
});

捕获错误并重新抛出 (Demo)

return throwError('This is an error!').pipe(
  catchError(error => {
    console.log("Error Caught", error);
    return throwError(error); // Catches the error and re-throws
  }),
).subscribe(data => {
  console.log("Got Data: ", data);
}, error => {
  console.error('error', error); // Observable stream has error so this prints
});

说实话 - 我从未见过这样的语法,我认为它是错误的:

.map(data => {
  return d;
}, error => {

error 是三个 Observable 的 subscribe() 方法回调之一。它触发一次 - 如果发生错误。但是 Rxjs catch 运算符 returns 一个 Observable。这是主要区别 - 您可以在其上中继以继续您的直播。