我如何在本地处理错误并跳过Angular HTTP拦截器?

  • 本文关键字:HTTP Angular 错误 处理 angular
  • 更新时间 :
  • 英文 :


我有一个AngularHttpInterceptor来捕获错误,并根据状态码显示适当的、通用的错误消息。

我有一个特殊的情况,我实际上期望和错误消息(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中添加一些逻辑,但是由于元数据上下文,这段代码可以更通用,并且保持简单。

例如:

Inapi.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();

Inerror.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();
})
);
}
}

最新更新