首页 > 解决方案 > 在 RxJS 中捕获不同的错误

问题描述

我有一个 Angular 的 HTTP 拦截器。应用程序使用 RxJS 计时器发送请求(短轮询)。它每 5 秒发送大约 10 个请求。我想使用拦截器来处理 502-504 状态码。我知道如何捕捉错误,但问题是轮询。

一旦我发送 10 个请求,我几乎同时收到 10 个错误。我想distinctUntilChanged()或至少take(1)以某种方式,但这两件事不能与catchError().

export class ErrorInterceptor implements HttpInterceptor {
    constructor(private readonly store: Store<AppState>) { }

    intercept(request: HttpRequest<string>, next: HttpHandler): Observable<HttpEvent<string>> {
        const errorCodes = [502, 503, 504];

        return next.handle(request).pipe(
            // take(1),
            // distinctUntilChanged(), // both lines not working, because error is thrown earlier
            catchError(err => {
                if (errorCodes.includes(err.status)) this.store.dispatch(connectionLost());

                return throwError(err);
            })
        );
    }
}

我知道我可以发送一个关于错误的新操作并使用distinctUntilChanged它的效果。但是我会在 Redux DevTools 中分派这个动作 10 次。我想避免这种情况。

有任何想法吗?

标签: angularrxjsangular-http-interceptors

解决方案


您可以使用materialize()dematerialize()。使用materialize()您可以抑制传入的错误并将它们作为错误通知不是错误本身)发送,然后您可以提供自定义comparefn 到distinctUntilChanged.

return next.handle(request).pipe(
  /* ... */
  materialize(), // Convert into notification
  distinctUntilChanged(yourCustomFn),
  /* ... */
  dematerialize() // Get back the `original value`
  /* ... */
);

推荐阅读