【问题标题】:Error not catch on Try Catch on Route level在 Route 级别的 Try Catch 上未捕获错误
【发布时间】:2020-02-18 20:57:54
【问题描述】:

我在我的函数中使用异步等待。我的控制器级别能够捕获错误,但是当返回到路由级别时。错误不是捕获,只返回数据:{}。我在这里做错了什么?

//route
router.get('/user', auth, async function(req,res){
try{
const userId = req.body.userId
const user = await UserController.getUser(userId)
res.status(200).send({data:user})
}catch(err){
res.status(400).send({message:err})
}
}
//Controller
exports.getUser = async function(userId ){
try{
const user = await User.findOne({_id:userId })
return user
}catch(err){
return err
}
}

【问题讨论】:

  • 也许代码没有抛出错误,而是发出事件。只是猜测
  • 当我尝试设置断点时,错误显示在控制器级别。但是当将错误返回到 Route 时。不跳转到捕捉

标签: node.js mongodb


【解决方案1】:

如果您已经在控制器级别捕获错误,您将无法再在路由捕获块中捕获它,除非您在控制器捕获块中捕获它后再次抛出它,即:

exports.getUser = async function (userId) {
  try {
    const user = await User.findOne({ _id: userId })
    return user
  } catch (err) {
    // throw the error again
    throw(err);
  }
}

但是这种方式很浪费,如果你打算在路由回调函数中处理错误,那么就不需要在控制器中捕获它。正确的做法是只编写控制器函数而不使用任何 try/catch 块:

exports.getUser = async function (userId) {
    return await User.findOne({ _id: userId })
}

然后像你已经在做的那样处理路由回调中的错误。

【讨论】:

    猜你喜欢
    • 2016-05-21
    • 2014-03-04
    • 2021-11-05
    • 2014-09-18
    • 2022-12-21
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多