1

Am working on an application where several types of errors can be thrown. For each different type of error, the node process must terminate with a different exit code.

At the moment I am throwing errors like:

throw new Error1('Failed, because of reason 1'); throw new Error2('Failed, because of reason 2');

However this causes the process to exit when the error is thrown with exit code 8 every time.

What I need is an elegant way to throw specific exit codes depending on which error is thrown. I.e. when I throw Error1, it should exit with code 1 and when I throw Error2 it should exit with code 2.

At the moment it just exits with code '8' every time.

I have looked at other articles and there are suggestions that using process.on('uncaughtException', ...); will work; and it does, however it requires 'catching' the error, re printing it out and then exiting.

Any suggestions?

Many thanks.

1
  • I did not realise those were Error1 and Error2 first time reading it. I have updated my answer to fix that. Commented Nov 11, 2015 at 18:43

1 Answer 1

4

The following code will let you do what you want:

Error8.prototype = Error.prototype
process.on('uncaughtException', handleErrors)
throw Error8("Bad news...")

function Error8(message) {
    this.name = "Error8"
    this.message = message || ''
    this.errorCode = 8
}
function handleErrors (e) {
    if (!e.errorCode) {
        console.log('Unknown exception occurred')
        process.exit(1)
    }

    console.log("ECODE-" + e.errorCode + ": " + e.message)
    process.exit(e.errorCode)
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.