LEARNNode CLI Automation

Node.js Process: Custom Error Handler

If you are working with Node.js then you should know about its process object. This object is quite important because it can help you to handle your production errors better than they usually appear.

In this article, I am going to talk about Node.js processes. I am also going to show you how you can custom handle your CLI errors with a node module I created. So without any further ado, let's jump in!

Node.js Process

It is an object which is an instance of EventEmitter. It has an on method which you can use to exit from any process in your project. You can also add some custom code that will be run before the process exits like this:

process.on('beforeExit', (code) => {
console.log('Process beforeExit event with code: ', code);
});
process.on('exit', (code) => {
console.log('Process exit event with code: ', code);
});
console.log('This message is displayed first.');

When this code will run, it will first log the console.log. After this, it is going to log the text in the terminal which is in the beforeExit process.on method. And finally, it will run the code in the exit process.on method.

exit process

You can read about the processes here. For now, I am going to show you a node module that will help you to custom handle your errors.

cli-handle-error

This is a node module I created that generates a nice looking error message in your CLI. Go ahead and install this package. For that, run the following command in your project terminal:

npm install cli-handle-error

Now require it in the index.js file of your CLI. And finally, just call it as a function.

You need to pass a couple of things as parameters to this function. For instance, as the first parameter, you would need to pass your error heading. After this, pass the error object.

const handleError = require('cli-handle-error');
handleError(`CUSTOM ERROR`, err);

If you want to hide the error, you can do that by just passing a false parameter to the handleError function.

handleError(`CUSTOM ERROR`, err, false);

You also have the option to not exit your CLI if your user encounters an error. For that, just pass another false as the fourth parameter to this handleError function.

handleError(`CUSTOM ERROR`, err, false, false);

Wrapping Up

This custom error handling improves your CLI experience. It allows your users to understand more about the error they are receiving. Probably it is something at their end like they have no internet access whatsoever when running your CLI. So go ahead and install this package and use it in your CLIs.

Posted by Saad (It's a work in progress: Needs copy editing review by Awais.)