Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I throw an exception after exhausting RxJs retryWhen operator attempts?

I want to catch the exception in subscribe but the result is not being as expected.

this.userService.isUsernameValid (username)
      .pipe (
          catchError (err =>
          {
            return throwError (err);
          }),
          retryWhen (errors =>
              errors.pipe (
                  delay (2500),
                  take (4),
                  concatMap (() => throwError ('Network error'))
              )
          )
       )
      .subscribe (
          data =>
          {
            //
          },
          error =>
          {
            console.log (error)
          });

I would like the exception to be thrown only if all attempts fail.

The code above only makes the first request and in case of an error throws the exception (does not redo the request).

If I remove the concatMap the 4 attempts will be made but I will not be able to catch the error within the subscribe if none is successful.

Thanks in advance.

like image 479
Vinicius G Avatar asked Oct 20 '25 15:10

Vinicius G


1 Answers

You can rethrow the error yourself under certain condition. For example concatMap passes index parameter to its projection function you can use instead of take():

throwError("It's broken")
  .pipe(
    retryWhen(errors => errors.pipe(
      concatMap((e, index) => index === 4 ? throwError(e) : of(null)),
    )),
  )
  .subscribe({
    next: x => console.log(x),
    error: e => console.log('obs', e),
  });

Live demo: https://stackblitz.com/edit/rxjs-kyr8zp

like image 92
martin Avatar answered Oct 22 '25 04:10

martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!