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) {
Error.captureStackTrace(this);
this.message = message;
this.name = "MountainError";
}
MountainError.prototype = Object.create(Error.prototype);
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!