簡體   English   中英

Angular Http 攔截器:catchError 並返回成功

[英]Angular Http Interceptor: catchError and return success

我有一個捕獲錯誤的 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)
      })
    )

  }
}

您需要返回一個Observable<HttpEvent<any>>對象。 您可以通過使用next.handle(newReq)發出另一個請求來實現這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);
  })
 )
}

盡管不推薦這樣做,但可以使用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