DEV Community

Code[ish]

51. Best Practices in Error Handling

Julián Duque is a senior developer advocate here at Heroku. He attended the NodeConf EU conference in Ireland, and met up with Ruben Bridgewater, a software architect and core Node.js contributor. Julián and Ruben go over the history of Node.js (now in its tenth year), as well as how Ruben became involved with the Node.js project.

Ruben's focus on Node is providing its users with good developer experiences. As a consultant, he has seen how organizations frequently run into the same issues over and over. JavaScript is partly to blame here, as there are three different patterns for executing asycnhronous logic: callbacks, promises, and the new async/await syntactic sugar. He'd like to help people avoid problems by strengthening their understanding around proper error handling.

Ruben has several suggestions. First, he advises everyone to switch to using the async/await pattern of asynchronous code execution, which was introduced in Node 12. This allows errors to provide an async stack trace, which is more helpful in diagnosing errors than the obfuscated errors that come from promises. Second, he advises teams not to simply try-catch and rethrow errors. It's far more beneficial to abstract errors into individual classes (NotFoundError, NotPermittedError, etc), because it allows the programmer to identify immediately from the error name what went wrong.

From this abstraction, Julián and Ruben discuss its role in logging strategies. By having your errors defined as distinct classes, you can place all sorts of "generic" information in them as properties, such as the status code. With no additional programming labor, this data can be exposed in the logs for additional analysis.

Mostly, the best thing you can do is to think about errors while writing the code. For example, add tests for all the edge cases you may encounter. By investing more time upfront in the development process, you will save yourself from worries later on when the code hits production.

Episode source