我正在尝试处理我的 async
方法抛出的自定义错误,但 try catch
block 无法正常工作。
我认为我这样做的方式应该可行,但没有发现错误,程序通过在终端中显示它而终止。
这是它抛出错误的地方:
async setupTap(tap) {
const model = this.connection.model('Tap', TapSchema);
await model.findOneAndUpdate({ id: tap.id }, tap, (err, result) => {
let error = null;
if (!result) {
throw new Error('Tap doesn\'t exists', 404);
}
return result;
});
}
然后是错误处理代码:
async setupTapHandler(request, h) {
const tapData = {
id: request.params.id,
clientId: request.payload.clientId,
beerId: request.payload.beerId,
kegId: request.payload.kegId,
};
try {
await this.kegeratorApi.setupTap(tapData);
} catch (e) {
if (e.code === 404) return h.response().code(404);
}
return h.response().code(204);
}
有人可以帮助我吗?
我还看了其他主题:
Correct Try...Catch Syntax Using Async/Await
How to properly implement error handling in async/await case
最佳答案
如果您正在等待 promise ,则只能使用 await
成功等待异步操作。假设您使用的是 mongoose,我不太了解 mongoose,但是如果您向它传递回调,model.findOneAndUpdate()
似乎不会返回 promise。相反,它会执行并将结果放入回调中。
此外,从像这样的回调中执行 throw
只会将数据抛出到数据库(调用回调的代码)中,对您没有任何好处。要让 throw
做出拒绝的 promise ,您需要从异步函数的顶层抛出或从 .then()
或 .catch()
处理程序或在 promise 执行程序函数内。这就是 throw 拒绝 promise 的地方。
这里的关键是您要使用数据库的 promise 接口(interface),而不是回调接口(interface)。如果您不传递回调,那么它会返回一个查询,您可以使用 .exec()
来获得一个 promise ,然后您可以将其与 await
一起使用。
此外,您没有构建一个将 .code
属性设置为 404 的错误对象。错误对象构造函数不支持该属性,因此如果您想要那个属性,你必须手动设置它。
我建议这样做:
async setupTap(tap) {
const model = this.connection.model('Tap', TapSchema);
let result = await model.findOneAndUpdate({ id: tap.id }, tap).exec();
if (!result) {
let err = new Error('Tap doesn\'t exists');
err.code = 404;
throw err;
}
return result;
}
或者,这里只有一个异步操作,使用 await
确实没有太大好处。你可以这样做:
setupTap(tap) {
const model = this.connection.model('Tap', TapSchema);
return model.findOneAndUpdate({ id: tap.id }, tap).exec().then(result => {
if (!result) {
let err = new Error('Tap doesn\'t exists');
err.code = 404;
throw err;
}
return result;
});
}
关于javascript - 异步/等待错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48859705/