【问题标题】:Is there any problem in handling 'throw error' inside try-catch in async await?在异步等待中处理 try-catch 中的“抛出错误”是否有任何问题?
【发布时间】:2020-03-08 23:59:59
【问题描述】:

我有一种使用 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语句检查空数组的方式是否有效?有没有更好的办法?

【问题讨论】:

    标签: javascript node.js error-handling async-await try-catch


    【解决方案1】:

    您正在抛出一个错误,但没有人能捕捉到它。当您创建 async 函数时,它会返回一个承诺。因此,当您抛出错误但未捕获它时,该函数将返回一个被拒绝的承诺。这就是您收到UnhandledPromiseRejectionWarning 的原因。当您使用 async/await 时,您必须使用 try-catch 捕获 Promise 拒绝。

    【讨论】:

    • 感谢您的回复。那么可以把它扔进try-catch吗?我认为这将是低效的。
    • 我看不出它效率低下的任何原因。
    猜你喜欢
    • 2018-12-20
    • 2021-01-12
    • 2016-01-26
    • 2019-02-11
    • 2022-01-19
    • 1970-01-01
    相关资源
    最近更新 更多