0

I want to build api resful, and I want to catch error when I throw error, but it is not working

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

});

When my_id is not in database, I cant not catch error and response json app.js

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

});
1
  • How are you catching the exception?? Simple try.. catch works in js. Commented Dec 29, 2014 at 11:37

1 Answer 1

2

You don't need to throw an error as it halts the execution of the whole script.

With express you can just pass the error to the next function and you error catcher will work.

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);
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.