【问题标题】:Handle promise error in class constructor [duplicate]处理类构造函数中的承诺错误[重复]
【发布时间】:2020-04-22 15:43:15
【问题描述】:

我的类构造函数调用了一个连接到服务的承诺。如果连接失败,如何捕获错误?我创建类实例的调用被包装在一个 try catch 块中,但它没有从 promise 中得到错误。像这样……

const client = require('aService')

try{let s = new Service()}
catch(e){console.log(`instance error ${e}`)

class Service{

    constructor(){
      this.connection = client.login()
         .then(){
            ...
          }
         .catch(e=>{
            console.log(`promise error ${e}`
            return e
           })
    }

控制台会记录“promise error”,但不会记录“instance error”,我需要这样才能干净利落地处理类实例失败。

非常感谢

【问题讨论】:

    标签: javascript promise


    【解决方案1】:

    Promise 已分配给 this.connection,但您在构造函数中 .catching 错误。只有当您可以对它做某事时才能更好地捕捉错误 - 也就是说,在外部Service 的消费者中。因此,只需将 .catch 从构造函数移动到您创建服务的正下方:

    const client = require('aService')
    
    class Service {
      constructor() {
        this.connection = client.login()
          .then(() => {
            // ...
          });
      }
    }
    
    
    let s = new Service()
    s.connection.catch((e) => {
      console.log(`connection error ${e}`)
    });
    

    或者使用awaittry/catch:

    const client = require('aService')
    
    class Service {
      constructor() {
        this.connection = client.login()
          .then(() => {
          // ...
        });
      }
    }
    
    
    (async () => {
      let s = new Service()
      try {
        await s.connection;
        // connection done
      } catch(e) {
        console.log(`connection error ${e}`)
      }
    })();
    

    【讨论】:

      猜你喜欢
      • 2014-11-18
      • 1970-01-01
      • 2016-11-01
      • 2018-06-01
      • 2022-12-05
      • 2014-04-30
      • 2016-03-02
      • 1970-01-01
      • 2015-07-29
      相关资源
      最近更新 更多