Search code examples
node.jsasync-awaitthrowerror-code

Async function does exit with code 0 even if error was thrown


Does anyone know how to make an async function exit with an non-zero exit code if an error was thrown?

If a sync function throws an error, the NodeJS script exits with an error code:

sync.js:

'use strict'

const main = function () {
    throw Error('Something failed hard')
}

main()
$ node sync.js
> ... Error: Something failed hard ...

$ echo $?
> 130

But if I do the same with an async function, the error code is always 0:

async.js:

'use strict'

const main = async function () {
    throw Error('Something failed hard')
}

main()
$ node async.js
> ... UnhandledPromiseRejectionWarning: Error: Something failed hard ...

$ echo $?
> 0

The closest thing I was able to do was:

async2.js:

'use strict'

const main = async function () {
    process.exit(1)
    throw Error('Something failed hard')
}

main()
$ node async2.js

$ echo $?
> 1

But then the error won't be thrown as the script has already exited :-P

I'm using Node 12.8.3.

I guess that the script doesn't wait until the promise was rejected before it exits. But I have no idea how to make the async function wait as I can't use await outside of a function :-P


Solution

  • I found out that you don't need to use process.exit(<code>) but you can set the exit code that will be used when the script exits beforehand with process.exitCode = <code>.

    So this works:

    async3.js:

    'use strict'
    
    const main = async function () {
        process.exitCode = 1
        throw Error('Something failed hard')
    }
    
    main()
    
    $ node async3.js
    > ... UnhandledPromiseRejectionWarning: Error: Something failed hard ...
    
    $ echo $?
    > 1
    

    Thanks everyone for being my rubber duck!