Arnaud
Arnaud

Reputation: 85

Mongoose validation exception not caught

I'm setting up a user registration within a MEAN app. However, I'm struggling with error handling, especially with Mongoose validation.

In the following code, when I provide a wrong email to my API, exception thrown by mongoose is not caught in my block.

try {
    User.save(function (err, user) {
        if (err) throw err; //This exception in not catched :(

        res.status(200).json({
            _status: 200,
            _content: {
                message: "OK",
                data: user
            }
        });
    });
} catch (err) {
    res.status(400).json({
        _status: 400,
        _content: {
            message: err.toString()
        }
    });
}

How can I catch this exception?

Upvotes: 0

Views: 1349

Answers (1)

Yalamber
Yalamber

Reputation: 7580

why don't you do it this way instead:

User.save(function (err, user) {
  if (err) {
    return res.status(400).json({
        _status: 400,
        _content: {
            message: err.toString()
        }
    });
  }
  res.status(200).json({
    _status: 200,
    _content: {
      message: "OK",
      data: user
    }
  });
});

Your code won't work because try catch won't be able to catch exceptions thrown inside your callback.

Upvotes: 1

Related Questions