Angular Http拦截器:catchError并返回成功

时间:2019-02-07 13:46:54

标签: javascript angular

我有一个捕获错误的Http拦截器(Angular 7)。是否有可能捕获到错误并根据某种条件返回成功而不是错误?我当前的代码。

export class RequestInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).pipe(
      catchError( response => {
        if(someCondition) {
           //return something that won't throw an error
        }
        return of(response)
      })
    )

  }
}

1 个答案:

答案 0 :(得分:0)

您需要返回一个Observable<HttpEvent<any>>对象。您可以使用next.handle(newReq)

发出另一个请求来实现

例如,如果您要添加错误错误为401的Bearer授权标头,则可以这样做

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

return next.handle(request).pipe(
  catchError( response => {
    if(response.status === 401) {
       return next.handle(request.clone({
         setHeaders: { "Authorization": `Bearer ${token}` }
       }));
    }
    return throwError(response);
  })
 )
}