Returning caught error observable from catchError in HttpInterceptor causes error loop

自闭症网瘾萝莉.ら 提交于 2019-12-23 09:24:53

问题


I have a simple interceptor that handles requests and catches any http error using RXJS catchError. The second argument received in catchError is the caught observable. I want to, in some cases, return this error and let it propagate up to the error handler in the subscribe function. The problem is that returning th caught error causes an infinite loop (as seen in the example: https://stackblitz.com/edit/angular-u4gakr)

The intercept function in the interceptor where the catchError is stuck in a loop when reciving an HTTP error, like 404:

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

I have probably misunderstood something about the interceptor or RxJS catchError. Any suggestion?


回答1:


Turns out I needed to use return throwError(error) as returning the caught observable, or of(error) both failed to return it properly to the subscribe functions error handler.

The final code is then:

return next.handle(request)
  .pipe(
    catchError((error) => {
      console.log('Returning caught observable'); 
      return throwError(error);
    })
  );



回答2:


You can change the return to just be this and the subscribe will handle the error.

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> {
    const requestCopy = request.clone();
    return next.handle(request).pipe(catchError(error => {
      if (error.status === 404) {
        return throwError(error)
      } else {
        return of()
      }
    }))
  }

https://stackblitz.com/edit/angular-zz3glp



来源:https://stackoverflow.com/questions/51948677/returning-caught-error-observable-from-catcherror-in-httpinterceptor-causes-erro

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!