簡體   English   中英

如何在本地處理錯誤並跳過 Angular HTTP 攔截器?

[英]How can I handle an error locally and skip an Angular HTTP interceptor?

我有一個 Angular HttpInterceptor來捕獲錯誤並根據狀態代碼顯示適當但通用的錯誤消息。

我有一個我實際期望的特定情況和錯誤消息(UI 嘗試釋放對剛剛被刪除的資源的鎖定,所以我得到 404)。

在這種情況下,我想直接在進行 API 調用的地方處理錯誤,並跳過攔截器。

我試過這個:

releaseReviewerLock(itemType: EquipmentItemType, itemId: EquipmentItem["id"]): Observable<void> {
  return this.http
    .post<void>(`${this.configUrl}/${itemType.toLowerCase()}/${itemId}/release-reviewer-lock/`, {})
    .pipe(
      catchError(e => {
        if (e.status === HttpStatusCode.NotFound) {
          // We can ignore the 404 because the item has just been deleted, so there's nothing to release.
          return EMPTY;
        }
      })
    );
}

但不僅我的攔截器無論如何都被調用了,上面的catchError塊根本沒有執行(斷點沒有停止)。

我可以在不修改攔截器並保持類似單一職責的情況下實現我想要的嗎?

謝謝!

我們可以將 一些元數據上下文傳遞給HttpClient ,然后在HttpInterceptor中檢索它。

當然,這意味着在HttpInterceptor中添加一些邏輯,但是由於元數據上下文,這段代碼可以更加通用,並且保持簡單。

例如:

api.service.ts

this.httpClient
  .get('http://...', {
    context: new HttpContext().set(IGNORED_STATUSES, [404]),
  })
  .pipe(
    catchError((e) => {
      console.log('Error catched locally', e);
      return of(EMPTY);
    })
  )
  .subscribe();

error.interceptor.ts

export const IGNORED_STATUSES = new HttpContextToken<number[]>(() => []);

export class CustomHttpInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const ignoredStatuses = req.context.get(IGNORED_STATUSES);

    return next.handle(req).pipe(
      catchError((e: HttpErrorResponse) => {

        // if ignored statuses are set
        // and returned status matched 
        if (ignoredStatuses?.includes(e.status)) {
          // rethrow error to be catched locally
          return throwError(() => e);
        }

        // process error...
        console.log('error interceptor !!', e);
        return of();
      })
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM