如何在自定义运算符中抛出流错误?

How to throw stream error in custom operator?

我找到了我想使用的 cstom 运算符。

这是一个重试 http 请求的运算符。代码来自 Stephen Fluin:https://github.com/StephenFluin/http-operators/blob/master/operators/retryExponentialBackoff.operator.ts

问题是,如果在完成所有这些操作后,它不会在流中产生错误,只会完成。 我想让它抛出一个错误。怎么做? 我认为这部分应该修改:

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

这里是整个运营商的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;
  });
};

我会尝试像这样向订阅者添加错误冒泡:

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

因此,在您的 maxTries 计数用完后,错误会在下游发出。