【发布时间】:2018-07-29 07:21:43
【问题描述】:
我正在尝试处理我的 async 方法引发的自定义错误,但 try catch 块无法正常工作。
我认为我这样做的方式应该可以工作,但错误没有被捕获,程序通过在终端中显示而终止。
这里是它抛出错误的地方:
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
【问题讨论】:
-
是什么让你认为
new Error("string", 404)会导致e.code == 404? -
你是怎么调用这个函数的?
-
注意,你在
findOneAndUpdate的回调中抛出(并返回) - 所以,这无论如何都不会按预期工作 -
只要参考@JaromandaX 的 cmets,您就有了解决方案。
标签: javascript node.js error-handling promise async-await