Better error handling in JavaScript

How and why to use custom error types in JavaScript

Iain Collins
6 min readAug 13, 2018

Handling errors well can be tricky. How Error() historically worked in JavaScript hasn’t made this easier, but using the Error class introduced in ES6 can be helpful

Image © Quinn Dombrowski

Throwing errors in JavaScript

JavaScript supports try/catch/finally but the Error object it uses works differently from Exceptions in other languages and it doesn’t provide a way to catch Errors by type in the same way you can with Exceptions in Java or C# so it’s quite common for all Errors thrown in a project to be instances of Error.

Some vendors have implemented a conditional catch clause but it’s not a standard and is not currently widely supported in browsers.

As a result of not having a standard way to define errors — or to return them when throwing them from a server to a client — information about an error being returned is often lost, with projects featuring bespoke error handling.

Throwing errors in other languages

If you’ve ever used .NET/Mono you may appreciate how good the error handling behaviour is out of the box, especially for web services.

--

--