Uncaught Exceptions

If there’s one thing I’ve learned when working with NodeJS, it’s that uncaught exceptions are a good thing. The smallest typo or undefined index in an object can completely kill your application. That’s also a good thing.

When working with a long running process, if you catch all unexpected exceptions you never truly know what state your application is in. You could have crashed half way through updating a user, or half way through processing a billing receipt.

One I’ve encountered personally was iterating over a group of connected users on the server and updating their last seen time. An exception was thrown after the first user and none of the other users were updated. If I’d just swallowed the exception, I would never have noticed it.

By all means, use process.onUncaughtException! It’s a great tool when used correctly. In every project, I attach a function to it which logs the exception’s stack trace, waits 500 milliseconds and kills the process itself (using process.exit(-1)). Not only do we record the exception and wait a short time to prevent spinning, but we also shut down the application, safe in the knowledge that when it starts up again it’ll be in a well defined state that we know how to deal with.

TL;DR

During long running processes catch all the exceptions. Log the exception + stack trace then kill the process yourself. Uncaught exceptions = unknown state.

Michael is a polyglot software engineer, committed to reducing complexity in systems and making them more predictable. Working with a variety of languages and tools, he shares his technical expertise to audiences all around the world at user groups and conferences. You can follow @mheap on Twitter

Thoughts on this post

Leave a comment?

Leave a Reply