处理类构造函数中的Promise错误

时间:2020-01-04 09:07:02

标签: javascript promise

我的类构造函数调用一个连接到服务的Promise。如果连接失败,如何捕获错误?我创建类实例的调用包装在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”(实例错误),这是我所需要的,以便可以干净地处理类实例失败。

非常感谢

1 个答案:

答案 0 :(得分:0)

Promise已分配给this.connection,但是您正在.catch构造函数中出错。最好仅在您可以使用它做某事时(也就是说,在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}`)
  }
})();