【问题标题】:Why does catch() block in mongoose query not exit the function when returning next(err)?为什么猫鼬查询中的catch()阻塞在返回next(err)时不退出函数?
【发布时间】:2021-04-29 17:08:52
【问题描述】:

我的快速路由器正在调用这个基本函数。

export const createThing = async(req,res,next) => {
    const {body} = req;
    const thing = await Thing.create(body).catch(err=>next(err));
    
    console.log('should ignore me on error')

    res.send(tran);
};

我有意按照Thing 模型的要求发送一个包含不完整字段的正文,它在 catch 块中触发了一个错误,这反过来又触发了我现有的所有错误中间件,但是,我希望它退出函数,因为我在捕获时返回next(err),但它仍然继续函数的其余部分。

我尝试删除const thing =,以便我没有将查询/捕获的结果返回到变量,而是将其作为await Thing.create(...).catch(...) 简单地执行,而这解决了我的错误报告中的其他问题,我在这里没有提及,它仍然是 console.logging '应该忽略我的错误'。

所以我的问题是为什么函数在捕获错误时不退出?我应该以某种方式手动执行此操作吗?我不只是调用 next(err) 我在 catch 块中返回它,而且我希望它不会继续执行该函数,然后会出现其他错误,因为我使用 res.send() 设置标题,我想要它出错时退出函数。

【问题讨论】:

    标签: node.js express mongoose error-handling


    【解决方案1】:

    .catch 会将拒绝的 Promise 转换为解析为从 .catch 返回的值的 Promise。您当前的代码,当.create 拒绝时,会产生以下表达式:

    Thing.create(body).catch(err=>next(err));
    

    成为一个解决next(err)返回的Promise。

    由于 Promise 解决(并且不拒绝),const thing = await // ... 不会抛出;执行流程将照常继续。

    您可以让.catch 在出现错误时返回错误,并在await 之外检查:

    const thing = await Thing.create(body).catch(err => { next(err); return err; });
    if (thing && thing instanceof Error) {
      return;
    }
    

    或者直接使用.then:

    export const createThing = async (req, res, next) => {
        const { body } = req;
        Thing.create(body)
            .then(() => {
                console.log('should ignore me on error')
                res.send(tran);
            })
            .catch(err => next(err));
    };
    

    【讨论】:

    • 谢谢!第一句话让我明白了很多,一个非常扎实和简洁的解释。干杯!
    猜你喜欢
    • 2019-09-17
    • 2018-03-07
    • 2018-05-26
    • 2020-02-03
    • 2017-10-10
    • 2019-03-24
    • 2020-06-29
    • 1970-01-01
    • 2018-11-18
    相关资源
    最近更新 更多