node-custom-error
Custom errors and exceptions in Node.js
Install
$ npm install custom-error-generator --save
Usage
var createCustomError = ;var ValidationError = ;var HTTPError = ; throw 'Required';
The generator function supports the following parameters:
-
name
{String} (required) - A custom name for this error type, which is printed when logging and in stack traces -
data
{Object} (optional) - Additional properties to attach to the error, in key=value pairs or as object descriptors -
Constructor
{Function} (optional) - A function to inherit from. Allows for additional methods and properties to be defined on your custom errors
The errors created by the generated functions are identical to built-in Error objects, with additional features such as:
Custom properties can be attached and accessed at run time:
var error = 'Uh oh';console; // prints 500 Server Error
Formatting
Similar to console.log
, the custom error message will be formatted from all available string and number arguments, using util.format
:
var error = '%s: %s' 'Missing Field' 'name';console; // prints ValidationError: Missing Field: name
Wrapped errors
Other error objects can be passed in as arguments, which augment the original error stack trace with their own stack traces:
var error = 'Missing field';var serverError = 'Something went wrong' error;console;
outputs:
HTTPError: Something went wrong at Context.<anonymous> at callFn at Hook.Runnable.run at next at Object._onImmediate at processImmediate [as _immediateCallback] ValidationError: Missing field at Context.<anonymous> at callFn at Hook.Runnable.run at next at Object._onImmediate at processImmediate [as _immediateCallback]
Multiple error objects are allowed to be passed, and are processed in order.
JSON support
Errors can also be serialized into JSON format by using error#toJSON();
. This will enumerate all of the hidden and custom properties, and also format the stack trace into an array of individual lines:
console; // or console.log(JSON.stringify(error));
outputs
Custom Constructor
Finally, a custom function can be passed in as a 3rd argument. This will allow you to modify the custom error prototype without having to modify the original native Error prototype:
var HTTPError = ;var error = 'You do not have permission' 403;console;// result: HTTPError: You do not have permission [ 403, "Forbidden" ]
Notes
Care is taken to preserve the built-in error handling behavior as much as possible, supporting:
-
custom instanceOf Error
-
Error.prototype.isPrototypeOf(custom)
-
util.isError(custom)
-
custom = generator('message')
-
custom = new generator('message');
In other words, you shouldn't have to worry about these errors affecting your syntax or existing code. Simply drop in place for any existing errors you're throwing and it should work just the same.