42

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?

3 Answers 3

58

Using a return is the correct way to stop a function executing. You are correct in that process.exit() would kill the whole node process, rather than just stopping that individual function. Even if you are using a callback function, you'd want to return it to stop the function execution.

ASIDE: The standard callback is a function where the first argument is an error, or null if there was no error, so if you were using a callback the above would look like:

var thisIsTrue = false;

exports.test = function(request, response, cb){

    if (thisIsTrue) {
        response.send('All is good!');
        cb(null, response)
    } else {
        response.send('ERROR! ERROR!');
        return cb("THIS ISN'T TRUE!");
    }

    console.log('I do not want this to happen. If there is an error.');

}
1
  • 1
    Excellent answer @Tim Brown. Thanks for the bonus explanation of the standard callback.
    – AJB
    Mar 12, 2014 at 21:52
22

You can use process.exit() to immediately forced terminate a nodejs program.

You can also pass relevant exit code to indicate the reason.

  • process.exit() //default exit code is 0, which means *success*

  • process.exit(1) //Uncaught Fatal Exception: There was an uncaught exception, and it was not handled by a domain or an 'uncaughtException' event handler

  • process.exit(5) //Fatal Error: There was a fatal unrecoverable error in V8. Typically a message will be printed to stderr with the prefix FATAL ERROR


More on exit codes

1
  • 1
    It's what I need
    – Mahefa
    Mar 4, 2021 at 21:10
6

You should use return, which will help you respond to what happened. Here's a bit cleaner version, basically first validate whatever you want to validate, rather than encapsulating everything in if{}else{} statements

exports.test = function(request, response, cb){

    if (!thisIsTrue) {
        response.send('ERROR! ERROR!');
        return cb("THIS ISN'T TRUE!");
    }

    response.send('All is good!');
    cb(null, response)

    console.log('I do not want this to happen. If there is an error.');

}

Another way would be to use throw

exports.test = function(request, response, cb){

    if (!thisIsTrue) {
        response.send('ERROR! ERROR!');
        cb("THIS ISN'T TRUE!");
        throw 'This isn\'t true, perhaps it should';
    }

    response.send('All is good!');
    cb(null, response)

    console.log('I do not want this to happen. If there is an error.');

}

Finally, examples that would stop entire app from further execution:

a) Throw an error, which will also help you debug the app (wouldn't completely stop the app, if the test() function was wrapper in try{}catch(e){}):

throw new Error('Something went wrong')

b) Stop script execution (works with Node.js):

process.exit()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.