XError
A utility class extending error that provides other useful features for standardized
error codes and handling. It inherits from Error and is compatible with it.
Error Codes
XError objects contain a machine-readable error code as well as a human-readable message. By convention,
error codes are lowercase, underscore_separated strings, such as internal_error
. Registered error
codes are available as constants on the XError object, with the names uppercased. The common error
codes are listed here
and you can register your own (see below).
Data
XError objects contain both a data
field and a privateData
field. These are intended to be set to
objects that contain extra data about the error. privateData
is used for information that should
not be displayed to a user.
Cause
XError objects can contain a "cause" error, similar to exception chains in languages such as Java. Causes
can be either an XError or an Error.
Fields
xerror.code
- The string error code, like internal_error
xerror.message
- Human-readable error messagexerror.data
- Object containing extra data about the errorxerror.privateData
- Object containing sensitive data about the errorxerror.cause
- XError or Error instance that triggered this errorxerror.stack
- Stack trace of where this error is constructed
Constructing
var XError = require('xerror');
new XError(XError.NOT_FOUND);
new XError('Something bad happened');
new XError(XError.BAD_REQUEST, 'You did something wrong');
new XError(XError.BAD_REQUEST, 'Something was wrong with your call', causeError);
new XError(XError.INVALID_ARGUMENT, { name: 'id', value: 'somethinginvalid' });
new XError(
XError.ACCESS_DENIED,
'Error validating account credentials',
{ username: 'crispy1989' },
{ password: 'password123' },
new Error('validation error')
);
XError.wrap(otherXError);
doSomething(function(error) {
if(error) return cb(XError.wrap(error));
});
Registering custom error codes
Error codes should be registered before being used. You can also register additional properties with the error code.
XError.registerErrorCode('my_custom_code', {
message: 'Custom Default Error Message',
http: 499
});
var error = new XError(XError.MY_CUSTOM_CODE, ...);
XError.registerErrorCode('item_missing', { aliasOf: XError.NOT_FOUND });
XError.registerErrorCodes({
custom_code_1: { message: 'Message for Custom Code 1' },
custom_code_2: { message: 'Message for Custom Code 2' }
});
You can also fetch these informational object about error codes:
var info = XError.getErrorCode(XError.NOT_FOUND);
var listOfCodes = XError.listErrorCodes();