Nodejs Extend Error
Contents |
by Alex R. Young on January 30th, 2014. Featured node errors The Art of Error Posted by Alex R. Young on January 30th, 2014.
Node Js Custom Error
Error was originally a character in the hit video game, "Zelda". I es6 extend error like to define a lot of objects that inherit from Error. I find it helps me to track
Javascript Custom Error Es6
down issues -- post-mortem -- but also to clearly handle expected errors. Sometimes writing error handling code feels like a chore, but it shouldn't be an afterthought. Well-designed and well-tested es6 custom error errors will help you maintain projects, but also help users figure out what to do when things go wrong. When it comes to using Error, I've found two bad practices that should be avoided: new Error is used instead of a subclass. Error is avoided altogether because "exceptions are bad". Let's look at how to avoid these issues and use errors error.capturestacktrace mdn properly. Subclassing Error Subclassing errors is easy with Object.create or util.inherits (in Node). Here's how you do it in Node: var assert = require('assert'); var util = require('util'); function NotFound(message) { Error.call(this); this.message = message; } util.inherits(NotFound, Error); var error = new NotFound('/bitcoin-wallet not found'); assert(error.message); assert(error instanceof NotFound); assert(error instanceof Error); assert.equal(error instanceof RangeError, false); The assertions check that the expected property was set (message), and error is an instance of NotFound, Error, but not RangeError. If you were using this with Express, you could set other properties to make the error more useful. This is great when passing errors to next() in routes. When dealing with errors at the HTTP layer, I like to include a status code: function NotFound(message) { Error.call(this); this.message = message; this.statusCode = 404; } Now you could have error handling middleware that handles errors in a more DRY fashion: app.use(function(err, req, res, next) { console.error(err.stack); if (!err.statusCode || err.statusCode === 500) { emails.error({ err: err, req: req }); } res.send(err.statusCode || 500, err.message); }); This will send the HTTP status code to the
Node.js and wished it should be this simple? var MyError = Error.extend('MyError'); http://dailyjs.com/2014/01/30/exception-error/ throw MyError('wow') installation npm install extend-error and in your app.js, just require('extend-error'). It will provide you an extend() method for the Error type. syntax extend() takes https://www.npmjs.com/package/extend-error two arguments : subTypeName & errorCode [optional] it returns the newly created error type more examples for a web app something useful var AppError = Error.extend('AppError', 500);var ClientError = Error.extend('ClientError', 400); extend ClientError further for specific http types var HttpNotFound = ClientError.extend('HttpNotFoundError', 404);var HttpUnauthorized = ClientError.extend('HttpUnauthorized', 401); throwing errors throw new AppError('unable to connect db due to error: ' + err); throw new ClientError({'message':'required field missing', field: 'email'}) throw new HttpNotFound('no post found with id: ' + id); throw new HttpNotFound({'message': 'no such post', 'id': id}); don't worry when you forget 'new' throw ClientError('bad request'); instanceof throw an error in controller var err = HttpNotFound('user profile not found'); throw err; (or)callback(err) handle it easily in global error handler (in case of express.js error middleware) if (err instanceof ClientError) { //send out the actual message res.send(err.code, err.message);} else { //send out a generic message res.send(500, 'oops! something went wrong'); log.error(err);} Private packages
Query Strings Readline REPL Stream String Decoder Timers TLS/SSL TTY UDP/Datagram URL Utilities V8 VM ZLIB GitHub Repo & Issue https://nodejs.org/api/errors.html Tracker Mailing List Node.js v6.9.1 Documentation Index | View on single http://blog.hostilefork.com/error-handling-internal-badrequest-node/ page | View as JSON Table of Contents Errors Error Propagation and Interception Node.js style callbacks Class: Error new Error(message) Error.captureStackTrace(targetObject[, constructorOpt]) Error.stackTraceLimit error.message error.stack Class: RangeError Class: ReferenceError Class: SyntaxError Class: TypeError Exceptions vs. Errors System Errors Class: System Error error.code error.errno error.syscall custom error Common System Errors Errors# Applications running in Node.js will generally experience four categories of errors: Standard JavaScript errors such as:
weird, JavaScript Error objects are weird, and handling errors in Node.JS is weird. My knowledge of the error-handling landscape evolved as I worked on the Blackhighlighter server in Node. I'd make notes in the code about things I discovered, or raise points to come back and look at later. Now that I get the basics of Node's landscape fairly well, I'm going back and looking at foundational documents like Joyent's Error Handling in Node.js - Production Practices. But I did want a place to put the information I'd found, while getting it out of the code. (See Comments vs. Links on the Collaborative Web for details.) Error Stacks and Creation Locations The first thing to know about errors in JavaScript is that they shouldn't be strings. This article lays out a number of details worth knowing: http://www.devthought.com/2011/12/22/a-string-is-not-an-error/ A key here is that "The fundamental benefit of Error objects is that they automatically keep track of where they were built and originated." Or rather--they probably do, but it's not in the specification. Similarly, how they would expose that data (or if they would) is not standardized either. Before we get into cracking open that black box of Error... I'll point out something perhaps of interest. There is a wider vocabulary in the standard than just Error... you have six more standard Error constructors: EvalError - Creates an instance representing an error that occurs regarding the global function eval(). RangeError - Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range. ReferenceError - Creates an instance representing an error that occurs when de-referencing an invalid reference. SyntaxError - Creates an instance representing a syntax error that occurs while parsing code in eval(). TypeError - Creates an instance representing an error that occurs when a variable or parameter is not of a valid type. URIError - Creates an instance representing an error that occurs when encodeURI() or decodeURl() are passed invalid parameters. Which is a curious point; that if you wanted to throw an error indicating something was out of range, you could use a RangeError. It would record its source location like an Error would. I'm not sure how often people re-use these errors--it might be more confusing than anything. If you're going to make your own cus