Fjallbacka Fjallbacka - 3 months ago 17
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:

app.post("/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 {
res.status(201).json(doc.ops[0]);
}
});
});


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

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