Better error handling in JavaScript

How and why to use custom error types in JavaScript

Iain Collins


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.

If you are not familiar with the .NET/Mono stack bare with me here for a minute, we’ll be coming back to how it’s relevant in other contexts below.

Naming conventions

.NET has naming conventions for errors, like InputValidationException for input validation errors and SecurityException for permissions errors, which is great for encouraging consistency in error handling.

Serializing errors

Another great feature of .NET is that throwing an exception on the server in a web service can automatically throw that exception in a client using the service — whether the client is C#, Java, PHP or JavaScript.

This is possible thanks to the Web Services Description Language (WSDL), which defines how objects, including Exceptions, are serialized and has native support in some languages (including C# and PHP) and support via third party libraries in others (including Java and JavaScript).