Friday, March 14, 2014

Custom Error Objects in JavaScript

For an upcoming talk at Mountain West JavaScript I'm going to talk about some basics in error handling. One of the advanced techniques that's a bit more advanced is the idea of creating custom errors objects to pass through your callbacks.

Why Error objects?

When following the callback pattern it's really nice to be able to depend that your error will return data in a consistent format. Error objects give you 2 things that are super important: message and a stack trace. Here's an example:

The stacktrace is extremely important and is likely the reason why using standard error objects is so popular in node.

Why Custom Error Objects?

Despite the awesomeness of general error objects, sometimes you need more information. You may need an array of error messages or some kind of error code in addition to the error message. This is where custom error objects come into play.

Creating a Custom Error Object

This is the most succinct constructor I've found to create a custom Error in Node. Importantly it satisfies several criteria:
  • There is a message property which includes the error message
  • There is a stack track (as a string in the stack property)
  • The error type is included in the stack trace (which is based on the name property)
  • You legitimately inherit from Error (i.e. instanceof Error is true)
function MountainError(message) {
   this.message = message; = "MountainError";
MountainError.prototype = Object.create(Error.prototype);
So go ahead and create this new object and see what you get!

Your new error object includes all of the standard stuff that you'd see in an error (including the stack trace, but you can start fiddling with it, adding extra properties, etc).

Happy erroring!