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

Shi*_*hti 5 observable rxjs5 angular angular-httpclient

如果我有如下代码:

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);
});
Run Code Online (Sandbox Code Playgroud)

以及是否存在任何类型的错误,即POST请求失败,.map()成功回调中的某些错误或任何其他类型的错误。

这两个错误处理程序中的哪一个将在.map()或回调上被调用.catch()?是否取决于可能发生的错误的类型?

.map()是否总是因为.catch()操作员的存在而跳过错误回调?

Ted*_*rne 6

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

例子:

订阅错误处理程序(演示

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
});
Run Code Online (Sandbox Code Playgroud)

捕获错误(演示

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
});
Run Code Online (Sandbox Code Playgroud)

捕获错误并重新抛出(演示

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
});
Run Code Online (Sandbox Code Playgroud)