【问题标题】:Why exception is not caught by my promise's catch clause?为什么我的承诺的 catch 子句没有捕捉到异常?
【发布时间】:2020-11-06 17:55:28
【问题描述】:

我有这段代码,希望在这个异步方法中捕获所有异常。不知何故,发生了一个 url 异常,但它没有被 catch 子句捕获。我必须在它周围添加一个 try-catch 块来捕获该异常,不知道为什么,有人可以解释一下吗?

public async transform(
  ): Promise {
   const {result} = this.processUrl(url).catch(error => error);
   return result;
}


private processUrl(url: string): Promise {
  const targetHostname = new URL(url).hostname; // exception thrown here invalid url something
  // do something else ...
  return Promise.resolve(targetHostname);
}

我希望转换函数永远不会抛出异常,但是当我提供无效的 url 时,processUrl 方法会抛出一个异常,该异常以某种方式没有被转换函数捕获。 我必须这样做才能抓住它。

public async transform(
  ): Promise {
try {
   const {result} = this.processUrl(url).catch(error => error);
} catch(e) {
    // invalid url exception got caught
    return Promise.resolve(undefined);
}
   return result;
}

【问题讨论】:

    标签: reactjs asynchronous exception promise try-catch


    【解决方案1】:

    processURL() 不是async 函数。因此,它不会自动返回 Promise,也不会自动捕获异常并将其转化为被拒绝的 Promise。

    因此,如果在processURL() 的任何地方抛出异常,该异常只会作为同步异常向上传播。如果你想自己捕获那个同步异常,你需要一个 try/catch 来捕获它。

    或者,您可以将 processURL() 设为 async 函数,然后它会自动捕获任何同步异常并将它们转换为被拒绝的 promise,然后您可以像这样使用 .catch() 捕获:

    private async processUrl(url: string): Promise {
      const targetHostname = new URL(url).hostname; // exception thrown here invalid url something
      // do something else ...
      return Promise.resolve(targetHostname);
    }
    

    或者你可以手动捕捉它:

    private processUrl(url: string): Promise {
      try {
          const targetHostname = new URL(url).hostname; // exception thrown here invalid url something
          // do something else ...
          return Promise.resolve(targetHostname);
      } catch(e) {
          return Promise.reject(e);
      }
    }
    

    您也可能在这里遇到问题:

    const {result} = this.processUrl(url).catch(error => error);
    

    因为您的 processUrl() 函数设置为返回一个承诺。您需要使用 .then()await 从该承诺中获取价值。仅供参考,如果 processUrl() 实际上是完全同步的,那么当它可以直接返回一个值时,让它返回一个承诺只会让事情变得复杂。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      • 1970-01-01
      • 2020-01-08
      • 2012-02-24
      • 2013-04-20
      • 1970-01-01
      相关资源
      最近更新 更多