Say I've got this script:
var thisIsTrue = false;
exports.test = function(request,response){
if(thisIsTrue){
response.send('All is good!');
}else{
response.send('ERROR! ERROR!');
// Stop script execution here.
}
console.log('I do not want this to happen if there is an error.');
}
And as you can see, I'd like to stop the script from executing any downstream functions if there's an error.
I've managed to achieve this by adding return;
after the error response is sent:
var thisIsTrue = false;
exports.test = function(request,response){
if(thisIsTrue){
response.send('All is good!');
}else{
response.send('ERROR! ERROR!');
return;
}
console.log('I do not want this to happen if there is an error.');
}
But is that the 'correct' way to do things?
Alternatives
I've also seen examples that use process.exit();
and process.exit(1);
, but that gives me a 502 Bad Gateway
error (I assume because it kills node?).
And callback();
, which just gave me an 'undefined' error.
What is the 'correct' way to stop a node.js script at any given point and prevent any downstream functions from executing?