在 RxJS 中捕获明显的错误
Catching distinct errors in 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 次。我想避免这种情况。
有什么想法吗?
您可以使用 materialize()
和 dematerialize()
。使用 materialize()
您可以抑制传入错误并将它们作为 错误通知 ( 不是 错误本身)发送,然后您可以提供自定义compare
fn 到 distinctUntilChanged
.
return next.handle(request).pipe(
/* ... */
materialize(), // Convert into notification
distinctUntilChanged(yourCustomFn),
/* ... */
dematerialize() // Get back the `original value`
/* ... */
);
我有一个 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()
。使用 materialize()
您可以抑制传入错误并将它们作为 错误通知 ( 不是 错误本身)发送,然后您可以提供自定义compare
fn 到 distinctUntilChanged
.
return next.handle(request).pipe(
/* ... */
materialize(), // Convert into notification
distinctUntilChanged(yourCustomFn),
/* ... */
dematerialize() // Get back the `original value`
/* ... */
);