LEARNNode CLI Automation

Handle Unhandled Errors in a Node.js CLI

There are a lot of things that you need to consider when you are building a production-quality CLI. Your documentation should be perfect. Your CLI should not break if the user has a lower Node.js version. And finally, you need to take care of all the edge cases.

We are all humans and there can still be some edge cases that we might miss. Some of these cases break the whole CLI. This should not happen because then your repository will be filled with issues.

So let's take a look at how you can take care of it.

cli-handle-unhandled

I have written a node module just for handling these small edge cases. It's called cli-handle-unhandled. You only need to install it, import it in your project and call it and it will take care of everything.

Just run the following command in your terminal to install this node module:

npm install cli-handle-unhandled

I am going to go ahead and import it into our project and call it.

const unhandled = require('cli-handle-unhandled');
unhandled();

Now to test this, I am going to reject a promise without any try/catch block to see how it is going to be handled.

handle errors

As you can see that I have an error, a reason for the error, and then an error stack. This is going to make the debugging quite easier because our user is also going to copy-paste this in the issue.

Wrapping Up

You can never be too careful. Go ahead and use this package to handle all the unhandled edge cases in your CLI.

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