An article by Iain Collins on how and why to use custom error types in JavaScript. Handling errors can be tricky. How Error() historically worked in JavaScript hasn’t made this easier, but using the Error class introduced in ES6 can be very helpful.
In JavaScript some vendors have implemented a conditional catch clause but it’s not a standard and not 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.
The article dives into:
- Comparing how Throwing errors is done in other languages
- Defining error types in JavaScript
- Returning Error objects from Promises
- Serializing Error objects in JSON
JavaScript actually has a several core Error types by default, but they are quite niche and of limited usefulness for error handling in most applications.
However, with ES6 you can extend the Error class and define custom errors with their own behaviour – such as logging errors automatically – and you can choose what detail to add or include when returning an error. Good read!
[Read More]