name The error name. Mozilla Mozilla (node.js) (node.js) fileName Path to file that raised the error. lineNumber The line number in the file that raised the error. columnNumber The col number. stack The error execution stack.
error that occurs regarding the global function eval(). InternalError Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion". 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 decodeURI() are passed invalid parameters.
var CustomError = function() { Error.apply(this, arguments); this.customProp = true; }; util.inherits(CustomError, Error); Error is a function that returns a new Error object and does not manipulate this in any way
var util = require('util'); var CustomError = function(message) { Error.captureStackTrace(this, this.constructor); this.name = 'CustomError'; this.message = message; }; util.inherits(CustomError, Error); instanceof Error works Stack traces work as expected Can extend itself captureStackTrace() is v8 specific For web replace with local throw
var util = require('util'); var CustomError = function(message) { // Use V8's native method if available, otherwise fallback if ('captureStackTrace' in Error) { Error.captureStackTrace(this, CustomError); } else { this.stack = (new Error()).stack; } this.name = 'CustomError'; this.message = message; }; util.inherits(CustomError, Error); instanceof Error works Stack traces have actual file on second line Can extend itself
{ myroutine(); // may throw three types of exceptions } catch (ex) { if (ex instanceof TypeError) { } else if (ex instanceof RangeError) { } else if (ex instanceof EvalError) { } else { logMyErrors(ex); } }
Errors with an httpCode or similar attribute, set to 500 by default. Throw them or augment existing Error objects by defining the httpCode. Create an express error middleware handling those errors. Pipe all error handling to next
var customErrorHandler = function (err, req, res, next) { var httpCode = 500; httpCode = err.httpCode || httpCode; res.status(httpCode); // figure out what the client accepts if (helpers.isRequestJson(req)) { res.json(error); } else { res.render('error/' + error.httpCode, {error: error}); } }; // Express error handler must always be last // in all of your middleware app.use(customErrorHandler);