我的类构造函数调用一个连接到服务的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”(实例错误),这是我所需要的,以便可以干净地处理类实例失败。
非常感谢
答案 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}`)
});
或将await
与try
/ 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}`)
}
})();