Reputation: 35
In my NodeJS/MongoDB server I'm writing, I have a lot of API calls to store users and whatnot in the database. Mongoose has calls for MongoDB which, after doing a query, will return a callback function with an error (if there is one) and a document (if there is one to return).
I'm wondering if I should send the error to the user, throw it (stopping the whole server), or just send a 500 error.
Example:
accountDocument.save(function (err, account) {
if (err){
res.status(500).json(err); // Option 1 - sends DB error to user
res.status(500).end(); // Option 2 - just notifies there was a problem
throw err; // Option 3 - stops the server completely
}
else
res.status(200).json(account);
});
Which should I choose to do?
Upvotes: 1
Views: 175
Reputation: 708046
First off, you have to determine if something catastrophic is wrong with your server or database. If so, then you probably need at least some admin attention, maybe even a server restart and you should make sure you've coded something to recognize that situation and notify whoever needs to know or take some definitive action. That's all internal to your ops team responsible for your site - nothing to do with the end user.
For example, if your code goes to open a connection to the database before doing a query and you can't even get a connection to it, then there's something seriously wrong and other than delaying a bit and retrying, there's nothing else your code can do, but to make sure somebody is notified who can try to figure out why there's no connection to the database any more.
Then, the best practice I've seen is to communicate back to the end user in a professional manner the following:
Some sort of code that uniquely corresponds to this particular error situation. While this isn't very user-friendly and should never be the main error feedback, having such a code makes it a TON easier for a report of the specific error to get all the way back to the developer without getting mangled and to give the developer enough info that they might be able to see what code path caused this error. For example "ErrorCode: 901". If there's only one place in your code that could generate error 901, then the developer can immediately know where in their code to go looking or testing to see what's causing this.
Whether or not this issue needs to be reported. If your internal system has already logged and reported the issue and will likely bring it to someone's attention automatically, then you can tell the user that this has already been done and they do not need to call in or email in to report it. If not, then you may even ask them to report it so you can hear about it and know that something isn't working.
Upvotes: 1