Node.js Error module
Simple Node.js module to provide better error handling throughout an application.
Makes use of HTTP error codes to identify different error types.
Install
npm i -S @springworks/error-factory
API:
var ErrorFactory = require('error-factory');
create([code], [message], [...var_args])
Create an error with status code and message. The code is a HTTP status code and defaults to 500. Message can be any string but defaults to the name of the status code. Any extra arguments will be formated into the message.
var err = ErrorFactory.create(500, 'Unable to send email to %s', 'user@example.com');
err.code;
err.statusCode;
err.message;
err.json;
err.toJSON();
validationError([message], [...var_args])
ErrorFactory.validationError
is a shortcut for ErrorFactory.create(422, 'Validation Failed')
. The message can be replaced with different string.
var err = ErrorFactory.validationError();
err.code;
err.message;
err.toJSON()
Used by the JSON.stringify method for JSON serialization.
Appending error descriptions to the error.
err.appendMissingResource(resource)
This means a resource does not exist.
The resource param is the name of the resource, e.g. 'User'.
err.appendMissingField(resource, field)
This means a required field on a resource has not been set.
The field param is the name of the field, e.g. 'email'.
err.appendMissingFields(resource, fields)
Same as appendMissingField
but with an array of fields.
err.appendInvalidField(resource, field)
This means the formatting of a field is invalid. The documentation for the resource should be able to give more specific information.
err.appendResourceAlreadyExists(resource, field)
This means another resource has the same value as this field. This can happen in resources that must have some unique key.
var err = ErrorFactory.validationError();
err.appendMissingResource('Thing').
appendMissingField('User', 'name').
appendInvalidField('User', 'password').
appendResourceAlreadyExists('User', 'email');
var obj = err.toJSON();
{
message: 'Validation Failed',
errors: [{
resource: 'Thing',
field: undefined,
code: 'missing'
}, {
resource: 'User',
field: 'name',
code: 'missing_field'
}, {
resource: 'User',
field: 'password',
code: 'invalid'
}, {
resource: 'User',
field: 'email',
code: 'already_exists'
}]
};
Tests
Run npm test
to run complete unit tests with Istanbul code coverage.