Fjallbacka Fjallbacka - 1 year ago 90
Node.js Question

Do not execute following code if error callback

I am creating a REST api and I've defined this error handler:

function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({"error": message});

But I think it needs some kind of interruption so that the following code is not executed, because if I implement my post method like this:"/contacts", function(req, res) {
var newContact = req.body;
newContact.createDate = new Date();

if (!(req.body.firstName || req.body.lastName)) {
handleError(res, "Invalid user input", "Must provide a first or last name.", 400);
db.collection(CONTACTS_COLLECTION).insertOne(newContact, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to create new contact.");
} else {

The server crashes and the invalid insertion is made into the database. I could solve this problem with an else for the insertion part, but I wanted to know if there is a way of not doing the rest of the method if the function handleError gets called.

Answer Source

Simply edit your handleError function so that the last line will be:

 return res.status(code || 500).json({"error": message});

Or, in your /contacts handler :

if (!(req.body.firstName || req.body.lastName)) {
    return handleError(res, "Invalid user input", "Must provide a first or last name.", 400);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download