简体   繁体   English

如何在异步函数中引发异常?

[英]How do I throw exceptions inside async functions?

my use case is something like this, 我的用例是这样的,

  1. First I get the image path and restaurant id from the front-end. 首先,我从前端获取图像路径餐厅ID
  2. Then I check whether this restaurant has 5 images already. 然后,我检查这家餐厅是否已经有5张图片。 If yes I send and exception says "Sorry maxmimum number of images you can upload is 5." 如果是,我会发送异常消息说“抱歉,您最多可以上传5张图像”。
  3. I want to attach that error to my respond as well. 我也想将该错误附加到我的回复中。

This is my code. 这是我的代码。

 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) } } 

In the catch block console log it outputs the error.But after that it gives me an error 在catch块控制台日志中,它输出错误,但之后却给我一个错误

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块的异步函数,或者是拒绝了一个.catch()无法处理的承诺。

I'm wondering why I'm getting this error since what I throw is correctly output in the catch block's console log . 我想知道为什么我会收到此错误,因为我抛出的内容正确输出到catch block's console log

Because there is a typo. 因为有错字。 You should write 'res.status(...' instead of 'res.stauts'. This exception is not handled by 'try... catch...' expression. 您应该编写“ res.status(...)而不是“ res.stauts”。该异常不会由“ try ... catch ...”表达式处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM