繁体   English   中英

处理承诺链外的承诺拒绝

[英]Handling promise rejections outside the promise chain

我熟悉承诺的工作方式以及未处理的承诺拒绝是什么,但是我有一个案例,我很难准确地确定如何捕获这个特定的未处理的承诺拒绝错误。

我的目标是创建一个速率受限的重试处理程序,它可以与一系列顺序承诺函数内联。

我正在使用一个实现转换流的限制器类。 进入流的消息仅以速率受限的速率发出,该速率用于强制执行重试率。

我的重试处理程序实现了一个函数sendMessage ,该函数返回一个带有结果的承诺。 如果消息发送失败,重试处理程序应重试发送消息,直至达到指定的最大重试次数。 它还应该将传出消息限制为指定的速率。

重试处理程序实际上并不发出 API 请求本身,这是由注册的 API 处理程序函数(它是抽象实际 API 调用的第 3 方库)完成的。 API 可能会以以下两种方式之一失败:

  1. 调用直接失败,来自处理程序的承诺被拒绝并被sendMessage函数的 .catch 捕获

  1. API 处理程序不会失败,但处理程序返回的结果为空,在这种情况下, errorEmitter模块稍后会发出一个事件( errorEmitter模块扩展EventEmitter )。
class RetryMessageHandler extends Readable {

  constructor(msg, limit, interval, max, handler, errorEmitter) {
    super({objectMode: true});
    this._limiter = new RateLimiter(limit, interval);
    this._retryCount = 0;
    this._maxRetries = max;
    this._msg = msg;
    this._handler = handler;
    this._errorEmitter = errorEmitter;

    // The retry handler is intended as single use. The promise is
    // created and stored to deal with the 2 different rejection 
    // scenarios

    this._promise = new Promise((resolve, reject) => { 
      this._resolve = resolve; 
      this._reject = reject;
    });

    this.retryTrigger = this.retryTrigger.bind(this);
    this.sendMessage = this.sendMessage.bind(this);

    // catch the messages as they exit the rate limiter
    this._limiter.on('data', this.sendOrder);

    // add the listener for the message failed event
    this._errorEmitter.prependOnceListener('Sending Message Failed', this.retryTrigger);

    // allows send() to push messages into the rate limiter
    this.pipe(this._limiter);
  }

  // after instantiation of the retry handler this method is
  // called to send the message with retries
  sendMessage() {
    this._retryCount++;

    // attempt to send message via API message handler
    this._handler(this._msg)

      .then((result) => {

        // check if the result received was null
        if (result) {
          
          // remove the errorEmitter module listener
          this._errorEmitter.removeListener('Sending Message Failed', this.retryTrigger);

          // resolve the retry handler promise and return the 
          // result to the retry handler caller.
          this._resolve(result);
        }
      })
      .catch((err) => {
        
        // scenario 1: Message sending failed directly
        // Need to remove the errorEmitter to avoid triggering twice
        this._errorEmitter.removeListener('Sending Message Failed', this.retryTrigger);

        // Trigger the retry method
        this.send();
      })

    return this._promise;
  }

  // required function due to extending Readable
  _read(size: number) {
    /* no op */
  }

  // Scenario 2: Message sending failed indirectly.
  // This method that is called whenever the errorEmitter module
  // emits a 'Sending Message Failed' event
  retryTrigger(err) {
    // Trigger the retry method
    this.send();
  }

  // Handles the retry sending the message
  send() {

    // Check if we've already exceed the maximum number of retries
    if (this._retryCount >= this._maxRetries) {
      this._errorEmitter.removeListener('Sending Message Failed', this.retryTrigger);


      // THIS IS WHERE THE PROBLEM OCCURS
      // We need to throw an error because we've exceeded the max
      // number of retries. This error causes the unhandled promise rejection error
      throw new ExceededRetryCountError('Exceeded maximum number of retries', this._msg);
    }

    // if can retry we need to reset the errorEmitter listener
    this._errorEmitter.prependOnceListener('Sending Message Failed', this.retryTrigger);

    // Finally push the message into the rate limiter.
    // The message will come out the other side and call the
    // sendMessage() method and the whole thing starts over again
    this.push(this._msg);
  } 
}

最初,我没有抛出错误,而是使用this._reject(new ExceededRetryCountError('Exceeded maximum number of retries', this._msg)); 但这仍然有同样的问题。

我发现了这个相关的问题( How can you retry after an exception in Javascript when using promises? )但这仅处理在承诺链中发生故障时的重试情况。

我想我可能已经发现导致未处理异常的问题。 当返回承诺的函数抛出错误时,catch 语句在同一个滴答上执行。 如果在函数执行的同一个滴答上抛出错误,则必须已经分配了 catch 处理程序。 这通常是通过调用function().then( … ).catch(err) ,但是对于 promises 通常也可以通过let promise = function(); promise.then( ... ).catch(err)直接处理返回的 promise let promise = function(); promise.then( ... ).catch(err) let promise = function(); promise.then( ... ).catch(err) 在第二种情况下,虽然这将导致未处理的异常,因为在抛出错误时,catch 语句尚未分配给承诺。 附加 catch 语句后,它实际上会正确捕获错误,但未处理的拒绝警告已经触发。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM