【发布时间】:2020-11-22 10:14:45
【问题描述】:
我有一个异步回调函数,如果不满足某些条件会抛出错误。
但我收到以下错误
(节点:77284)UnhandledPromiseRejectionWarning:错误:未找到
UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。
我的代码:
async deleteItem(id: string): Promise<void> {
const ref = firestoreDB.collection("items").doc(id);
firestoreDB
.runTransaction(async (transaction: FirebaseFirestore.Transaction) => {
let doc = await transaction.get(ref);
if (doc.exists) {
transaction.delete(ref);
} else {
throw new NotFoundException();
}
})
.catch((err) => {
if (err instanceof NotFoundException) {
throw err;
} else {
throw new HttpException(
"Something went wrong",
HttpStatus.INTERNAL_SERVER_ERROR
);
}
});
}
从回调函数中抛出错误的正确方法是什么?
【问题讨论】:
-
尝试将异步回调函数实现包装在 try...catch 中
-
也许你在
transaction.delete(ref);之前忘记了await
标签: javascript node.js es6-promise