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!
Be advised that instanceof "lies".
ReplyDeleteThe best solution is to duck-type. See http://gunargessner.com/subclassing-exception/.
You are doing a great job. You inspire me to write for other. Thank you very much. I would like to appreciate your work for good accuracy and got informative knowledge from here.Python Training in Chennai
ReplyDeleteGracias por la información! es muy útil!
ReplyDeleteMarisco Gallego con productos como Bogavante azul
JavaScript Stack is a platform dedicated to sharing useful information, tutorials, tips, and resources related to JavaScript and web development. It helps beginners and developers learn concepts such as JavaScript programming, HTML, CSS, coding techniques, and modern web technologies through simple and easy-to-understand content.
ReplyDeleteThis website is powered by Blogger and created to provide helpful educational resources for developers and technology enthusiasts. JavaScript Full Stack Course
ReplyDeleteOur goal is to make web development easier to understand by sharing practical guides, examples, and useful programming knowledge in a clear and accessible way.