[英]Is there any problem in handling 'throw error' inside try-catch in async await?
我有一种使用 mongoose 将产品发布到 mongodb 的方法。 我正在使用异步等待而不是 then-catch 块。 我的代码:
const Category = require('../models/category');
exports.postProduct = async (req,res,next)=>{
//const userId = req.user.userId;
const userId = '5dca886a1ee97b07002de048';
// const category = req.body.category;
const category = ['bikes','cars'];
// const tags = req.body.tags;
const tags = ['wheels','vehicles','travel','s','s','s'];
//const imageUrl = req.body.imageUrl;
const imageUrl = ['https://picsum.photos/200/300','https://picsum.photos/200/300','https://picsum.photos/200/300'];
try {
if(tags.length>5){
const error = new Error('Select only 5 Tags');
error.statusCode = 406;
throw error;
}
if (!category || category === []){
const error = new Error('Selected category is empty, select category again');
error.statusCode = 406;
throw error;
}
const categoryFound = await Category.find({name: {$in:category}}).select('name');
if (categoryFound) {
const addProduct = new Product(
{ name : 'vehicle',
description:'Its a good vehicle',
categoryId: categoryFound,
productImageUrl: imageUrl,
creatorId:userId,
productRequirement:'buy',
tags:tags
});
const productSaved = await addProduct.save();
res.status(200).json({message:productSaved});
}else{
const error = new Error('Category not found!');
error.statusCode = 404;
throw error;
}
} catch (err) {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
}
};
catch 中的错误被我的 app.js 中的 express 中间件捕获。
//Error handling middleware
app.use((error, req, res, next) => {
const status = error.statusCode || 500;
const message = error.message;
res.status(status).json({ message: message, status: status });
});
这工作正常。 在这种特定情况下,当数组“标签”长于 5 时,我从 Postman(REST API 开发工具)的请求返回:
{
"message": "Select only 5 Tags",
"status": 406
}
当我尝试在 try-catch 之外使用“if”检查时,出现此错误:
UnhandledPromiseRejectionWarning: Error: Select only 5 Tags
at exports.postProduct (F:\project\controllers\products.js:17:23)
at Layer.handle [as handle_request] (F:\project\node_modules\express\lib\router\layer.js:95:5)
at next (F:\project\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (F:\project\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (F:\project\node_modules\express\lib\router\layer.js:95:5)
at F:\project\node_modules\express\lib\router\index.js:281:22
at Function.process_params (F:\project\node_modules\express\lib\router\index.js:335:12)
at next (F:\project\node_modules\express\lib\router\index.js:275:10)
at Function.handle (F:\project\node_modules\express\lib\router\index.js:174:3)
at router (F:\project\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (F:\project\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (F:\project\node_modules\express\lib\router\index.js:317:13)
at F:\project\node_modules\express\lib\router\index.js:284:7
at Function.process_params (F:\project\node_modules\express\lib\router\index.js:335:12)
at next (F:\project\node_modules\express\lib\router\index.js:275:10)
at F:\project\app.js:54:5
这种在 try-catch 中抛出错误以检查长度、使用 if 语句检查空数组的方式是否有效? 有没有更好的方法呢?
您正在抛出一个错误,但没有人能捕捉到它。 当您创建async
function 时,它会返回 promise。 因此,当您抛出错误但未捕获它时,function 将返回被拒绝的 promise。 这就是您收到UnhandledPromiseRejectionWarning
的原因。 当您使用 async/await 时,您必须使用 try-catch 捕获 promise 拒绝。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.