简体   繁体   English

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

[英]Angular Http Interceptor: catchError and return success

I have an Http Interceptor (Angular 7) that catches errors.我有一个捕获错误的 Http 拦截器(Angular 7)。 Is it possible to catch the error and based on some contidition, returns a success instead of the error?是否有可能捕获错误并根据某些条件返回成功而不是错误? My current code.我当前的代码。

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)
      })
    )

  }
}

You need to return an Observable<HttpEvent<any>> object.您需要返回一个Observable<HttpEvent<any>>对象。 You can achieve that by making another request using next.handle(newReq)您可以通过使用next.handle(newReq)发出另一个请求来实现这next.handle(newReq)

For example, if you want to add a Bearer authorization header if the error is 401, you can do like that例如,如果你想在错误是 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);
  })
 )
}

Even though this is not recommended, creating a success response from catchError can be done using HttpResponse class,尽管不推荐这样做,但可以使用HttpResponse class 从 catchError 创建成功响应,

return next.handle(request)
    .pipe(
        catchError((error: HttpErrorResponse) => {
            return of(new HttpResponse({ body: {}, status: 0 }));
        })
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM