在RxJS中捕获明显的错误

问题描述 投票:0回答:1

我有一个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次。我想避免这种情况。

有什么想法吗?

angular rxjs angular-http-interceptors
1个回答
0
投票

您可以使用materialize()dematerialize()。使用materialize()可以抑制传入的错误并将其作为错误通知(本身就是not错误)发送,然后可以向compare提供自定义的distinctUntilChanged fn。

return next.handle(request).pipe(
  /* ... */
  materialize(), // Convert into notification
  distinctUntilChanged(yourCustomFn),
  /* ... */
  dematerialize() // Get back the `original value`
  /* ... */
);
© www.soinside.com 2019 - 2024. All rights reserved.