What is error-ex?
The error-ex npm package is designed to create more customizable and informative error objects in JavaScript. It allows developers to extend the native Error type with additional properties and behaviors, making error handling and debugging more efficient.
What are error-ex's main functionalities?
Creating custom error types
This feature allows developers to create custom error types by extending the native Error object. The custom error can then be thrown with a specific message, making it easier to identify and handle specific kinds of errors in the code.
const ErrorEx = require('error-ex');
const MyError = ErrorEx('MyError');
throw new MyError('Something went wrong');
Adding properties to errors
This functionality enables the addition of custom properties to error objects. In this example, a 'code' property is added to a custom error type, which could be used to store HTTP status codes or other relevant error information.
const ErrorEx = require('error-ex');
const MyError = ErrorEx('MyError');
MyError.prototype.code = 404;
const errorInstance = new MyError('Resource not found');
console.log(errorInstance.code); // 404
Other packages similar to error-ex
verror
VError is a library for richer JavaScript errors. It allows chaining of errors, providing a way to wrap lower-level errors without losing the original context. Compared to error-ex, VError focuses more on error wrapping and context preservation.
http-errors
http-errors is a package for creating HTTP error objects. It is specifically tailored for use in web applications, providing a straightforward way to create errors with HTTP status codes. Unlike error-ex, http-errors is more specialized for HTTP applications.
node-error-ex
Easily subclass and customize new Error types
Examples
To include in your project:
var errorEx = require('error-ex');
To create an error message type with a specific name (note, that ErrorFn.name
will not reflect this):
var JSONError = errorEx('JSONError');
var err = new JSONError('error');
err.name;
throw err;
To add a stack line:
var JSONError = errorEx('JSONError', {fileName: errorEx.line('in {}')});
var err = new JSONError('error')
err.fileName = '/a/b/c/foo.json';
throw err;
To append to the error message:
var JSONError = errorEx('JSONError', {fileName: errorEx.append('in {}')});
var err = new JSONError('error');
err.fileName = '/a/b/c/foo.json';
throw err;
License
Licensed under the MIT License.
You can find a copy of it in LICENSE.