【问题标题】:catch exception when throw error using nodejs使用nodejs抛出错误时捕获异常
【发布时间】:2014-12-29 11:00:02
【问题描述】:

我想构建 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
    });

});

【问题讨论】:

  • 你是如何发现异常的?简单的try.. catch 在 js 中工作。

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


【解决方案1】:

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

使用 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);
        }
    });
});

【讨论】:

    猜你喜欢
    • 2016-02-17
    • 2018-04-05
    • 2013-06-24
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多