从HttpInterceptor中的catchError返回可观察到的捕获错误会导致错误循环

Jan*_*emb 5 rxjs angular rxjs6

我有一个简单的拦截器,可以处理请求并使用RXJS catchError捕获任何http错误。在catchError中收到的第二个参数是捕获的可观察值。在某些情况下,我想返回此错误,并使其传播到订阅函数中的错误处理程序。问题是返回捕获的错误会导致无限循环(如示例中所示:https : //stackblitz.com/edit/angular-u4gakr

接收HTTP错误(例如404)时,catchError陷入循环的拦截器中的拦截函数:

return next.handle(request)
  .pipe(
    catchError((error, caught$) => {
      console.log('Returning caught observable'); 
      return caught$;
    })
  );
Run Code Online (Sandbox Code Playgroud)

我可能误解了有关拦截器或RxJS catchError的某些信息。有什么建议吗?

Jan*_*emb 10

事实证明,我需要使用return throwError(error)as 返回捕获的可观察值,或者 of(error) 都无法将其正确返回到订阅函数错误处理程序。

最终的代码是:

return next.handle(request)
  .pipe(
    catchError((error) => {
      console.log('Returning caught observable'); 
      return throwError(() => new Error('The Error'));
    })
  );
Run Code Online (Sandbox Code Playgroud)