【问题标题】:Catching distinct errors in RxJS在 RxJS 中捕获不同的错误
【发布时间】:2020-04-03 01:42:51
【问题描述】:

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

有什么想法吗?

【问题讨论】:

  • 您考虑过使用materialize()dematerialize() 吗?使用materialze(),您可以抑制传入错误并将它们作为error notifications(不是错误本身)发送,然后您可以提供自定义compare fn 到distinctUntilChanged
  • 不知道这些运算符。谢谢! :) 你能把你的评论变成答案吗?我会将其标记为解决方案

标签: angular rxjs angular-http-interceptors


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多