我的用例是这样的,
- 首先,我从前端获取图片路径和餐厅 ID。
- 然后我检查这家餐厅是否已有 5 张图片。如果是,我发送,但异常显示“抱歉,您可以上传的最大图像数量为 5。”
- 我也想将该错误附加到我的回复中。
这是我的代码。
export async function upload_images_to_restaurant(req, res, next) {
try {
const data = req.swagger.params.body.value;
console.log("Data", data);
const restaurant_id = data.restaurant_id;
const count = await db.restaurant_images.count({
where: {
restaurant_id: restaurant_id
}
})
if (count >= 5) {
throw "Sorry maxmimum number of images you can upload is 5."
} else {
const upload = db.restaurant_images.create(data)
}
console.log("Count", count)
res.sendStatus(200);
} catch (error) {
console.log("Errors", error);
res.stauts(422).json(error)
}
}
在 catch block 控制台日志中它输出错误。但之后它给了我一个错误
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
我想知道为什么我会收到此错误,因为我抛出的内容在 catch block 的
控制台日志
中正确输出。
最佳答案
因为有错别字。您应该编写“res.status(...”而不是“res.status”。此异常不会由“try...catch...”表达式处理。
关于javascript - 如何在异步函数中抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52307379/