0

I have an Angular's HTTP interceptor. Application uses RxJS timer to send requests (short polling). Every 5s it sends around 10 requests. I want to use the interceptor to handle 502-504 status codes. I know how to catch errors, but the problem is polling.

Once I send 10 requests, I get 10 errors almost in the same time. I would like to distinctUntilChanged() or at least take(1) somehow, but both things does not work together with 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);
            })
        );
    }
}

I know I could dispatch a new action about the error and use distinctUntilChanged in its effect. But I will get this action dispatched 10 times in Redux DevTools. I would like to avoid that.

Any ideas?

2
  • Did you consider using materialize() and dematerialize() ? Using materialze() you can supress incoming errors and send them as error notifications(not errors per se) and then you could provide a custom compare fn to distinctUntilChanged. Commented Apr 2, 2020 at 13:59
  • 1
    Didn't know about these operators. Thanks! :) Can you convert your comment into answer? I will mark it as a solution Commented Apr 2, 2020 at 17:23

1 Answer 1

1

You could use materialize() and dematerialize(). Using materialize() you can suppress incoming errors and send them as error notifications(not errors per se) and then you could provide a custom compare fn to distinctUntilChanged.

return next.handle(request).pipe(
  /* ... */
  materialize(), // Convert into notification
  distinctUntilChanged(yourCustomFn),
  /* ... */
  dematerialize() // Get back the `original value`
  /* ... */
);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.