piernik
piernik

Reputation: 3657

How to throw stream error in custom operator?

I found cstom operator that I want to use.

This is an operator that retries http requests. Code is from Stephen Fluin: https://github.com/StephenFluin/http-operators/blob/master/operators/retryExponentialBackoff.operator.ts.

Problem is that if after all these reties it does not puts error in stream only completes. I want it to throw an error. How to do it? I think this part should be modified:

     error(err: any) {
        if (count <= maxTries) {
          subscription.add(scheduler.schedule(subscribe, initialWait * Math.pow(2, count++)));
        }
      },

Here is whole operator's class

/**
 * Repeats underlying observable on a timer
 *
 * @param maxTries The maximum number of attempts to make, or -1 for unlimited
 * @param initialWait Number of seconds to wait for refresh
 */
export const retryExponentialBackoff = (
  maxTries = -1,
  initialWait = 1,
  scheduler: SchedulerLike = asyncScheduler
) => <T>(
  source: Observable<T>
) => {
  return new Observable<T>(subscriber => {
    let count = 1;
    const subscription = new Subscription();

    const subscribe = () =>
      subscription.add(
        source.subscribe({
          next(value: T) {
            count = 1;
            subscriber.next(value);
          },
          error(err: any) {
            if (count <= maxTries) {
              subscription.add(scheduler.schedule(subscribe, initialWait * Math.pow(2, count++)));
            }
          },
          complete() {
            subscriber.complete();
          },
        })
      );

    subscribe();

    return subscription;
  });
};

Upvotes: 0

Views: 55

Answers (1)

Mark van Straten
Mark van Straten

Reputation: 9425

I would try to add the error bubbling to the subscriber like so:

error(err: any) {
  if (count <= maxTries) {
    subscription.add(scheduler.schedule(subscribe, initialWait * Math.pow(2, count++)));
  }
  else {
    subscriber.error(err);
  }
},

So that after your maxTries count have een exhausted the error is emitted downstream.

Upvotes: 2

Related Questions