使用nodejs抛出错误时捕获异常

时间:2014-12-29 11:00:03

标签: node.js error-handling uncaught-exception

我想构建api resful,我想在抛出错误时捕获错误,但它无法正常工作

controller.js

Article.findOne({_ id:my_id},function(err,article){

if(article === null){
   throw Error('Article is not found');
}else{
   res.status(200).json(article);
}

});

当my_id不在数据库中时,我无法捕获错误并响应json app.js

app.use(function(err, req, res, next) {
    res.status(200).json({
        'status' : 500,
        'messages' : err
    });

});

1 个答案:

答案 0 :(得分:2)

您不需要抛出错误,因为它会停止整个脚本的执行。

使用express,您只需将错误传递给next函数,错误捕获器就可以正常工作。

router.get('/', function(req, res, next) {
    Article.findOne({_id: my_id}, function(err, article) {
        if(article === null){
           var error = Error('Article is not found');
           next(error);
        }else{
           res.status(200).json(article);
        }
    });
});
相关问题