How to skip error with delay in RxJS with a right typescript infer?

I just want to log an error and skip this step, but with delay and with true typescript infer.

const fetch = () =>
  Math.random() > 0.5
    ? Promise.resolve("Success")
    : Promise.reject("Some error");

const x = timer(0, 1000).pipe(
  mergeMap(() => fetch()),
  catchError((err, caught) => {
    console.log("Error: ", err);
    return caught; // After this a pipe starts again, but without delay, because a timer starts with 0 !!!
  }),
);

x.subscribe((data) => {
  console.log(data);
});

I need to make a delay after caught error.

1 answer

  • answered 2019-10-15 19:31 Cookie Stealer

    Are you only looking to have a delay after an error is caught? The code you've provided might have an unintentional mistake in it, as the stream technically is ended after an error occurs. You can see what I mean by changing the return value to the proper error like this:

    const x = timer(0, 1000).pipe(
        mergeMap(() => fetch()),
        catchError((err) => { // "caught" is not needed, it isn't really anything.
          console.log("Error: ", err);
          return of(err); // If you return the error properly, the stream will end on error as expected behavior.
        }),
    );
    

    What I suspect you really want to do is to retry with a delay timer, and you can achieve so by doing this:

    const x = timer(0, 1000).pipe(
        mergeMap(() => fetch()),
        retryWhen(errors =>
            errors.pipe(
                tap(errors => console.log('Error: ', errors)),
                delayWhen(() => timer(3000))
            )
        )
    );
    

    This will retry whenever an error occurs after x seconds.