therror
therror is a library created for making node error management easy, customizable, interoperable and documentable.
It's written in ES6, for node >= 4
Therror errors are javascript errors
with sugar. You can use this library to create your application or library errors, and maintain fully interoperability with
others code.
The sugar is:
- variables: Add runtime information to your error messages
- extensibility: Pure javascript Error classes with easy ES6 mixins support
- nesting: Add the parent cause to your library errors
- notifications: Subscribe to events when an error is created: Log them in a single place.
- internationalization: Easy to hook your own i18n library to translate error messages
- predefined http errors: Standard HTTP Error classes for quick programming
With the help of their peer projects, you will have the opportunity to create a set of documents in various formats to
satisfy the needs of several teams (operations, delivery, final users, developers, ...) but only maintaining one documentation in
the best place ever: your source code.
Try therror online
Installation
npm install --save therror
Usage
const Therror = require('therror');
class InvalidParamError extends Therror {}
try {
throw new InvalidParamError('${value} is not valid value for ${id}', {value: 12, id: 'offset'});
} catch (err) {
throw new Therror(err, `Invalid param "${err.id}"`));
}
Create your own errors
const Therror = require('therror');
class InvalidParamError extends Therror {
constructor(props) {
super(props);
this.message = '${value} is not valid value for ${id}';
this.statusCode = 400;
}
}
let err = new InvalidParamError({ value: 12, id: 'offset' });
console.log(err);
Adding error causes
const Therror = require('therror');
try {
throw new Error('3rd Party error');
} catch (err) {
let catchedError = new Therror(err, 'There was a problem with 3rd Party');
console.log(catchedError.cause());
}
You can also use logops, an error friendly logger that incorporates support off the shell for printing error causes.
Server Error classes
Common use case for your Server Errors.
Includes Therror.Notificator
, Therror.Loggable
, Therror.WithMessage
and Therror.HTTP
mixins. If you are using express, therror-connect error handler might be useful
let err = new Therror.ServerError.NotFound('The user ${user} does not exists', {
user: 'Sarah'
});
res.statusCode(err.statusCode);
res.json(err.toPayload());
toPayload()
method is meant to get the final response to the client.
When the error statusCode >= 500
, it will set in the payload response
a generic response to hide the implementation details to the user, while
having the original properties untouched to log the error as it was defined
let err = new Therror.ServerError.ServiceUnavailable('BD Misconfigured');
console.log(err);
res.statusCode(err.statusCode);
res.json(err.toPayload());
Create your own
class UserNotFound extends Therror.ServerError({
message: 'User ${username} does not exists',
level: 'info',
statusCode: 404
}) {}
let error = new UserNotFound({ username: 'John Doe' });
The following classes have been defined in Therror.ServerError
{
'400': 'BadRequest',
'401': 'Unauthorized',
'402': 'PaymentRequired',
'403': 'Forbidden',
'404': 'NotFound',
'405': 'MethodNotAllowed',
'406': 'NotAcceptable',
'407': 'ProxyAuthentication Required',
'408': 'RequestTimeout',
'409': 'Conflict',
'410': 'Gone',
'411': 'LengthRequired',
'412': 'PreconditionFailed',
'413': 'RequestEntityTooLarge',
'414': 'RequestUriTooLarge',
'415': 'UnsupportedMediaType',
'416': 'RequestedRangeNotSatisfiable',
'417': 'ExpectationFailed',
'418': 'ImATeapot',
'422': 'UnprocessableEntity',
'423': 'Locked',
'424': 'FailedDependency',
'425': 'UnorderedCollection',
'426': 'UpgradeRequired',
'428': 'PreconditionRequired',
'429': 'TooManyRequests',
'431': 'RequestHeaderFieldsTooLarge',
'451': 'UnavailableForLegalReasons',
'500': 'InternalServerError',
'501': 'NotImplemented',
'502': 'BadGateway',
'503': 'ServiceUnavailable',
'504': 'GatewayTimeout',
'505': 'HTTPVersionNotSupported',
'506': 'VariantAlsoNegotiates',
'507': 'InsufficientStorage',
'509': 'BandwidthLimitExceeded',
'510': 'NotExtended',
'511': 'NetworkAuthenticationRequired'
}
Internationalization
const Therror = require('therror');
class InvalidParamError extends Therror {
constructor(props) {
super(props);
this.message = '${value} is not valid value for ${id}';
}
}
try {
throw new InvalidParamError({ value: 12, id: 'offset' });
} catch (err) {
err.message = i18n('es-ES', err.name);
console.log(err);
}
Bluebird ready
const Therror = require('therror');
const Promise = require('bluebird');
class InvalidParamError extends Therror {}
Promise.try(() => {
throw new InvalidParamError('Invalid parameter');
}).catch(InvalidParamError, err => {
});
Add functionality to your errors by using mixins
Shared messages across all instances
DRY. Rehuse the errors customizing only metadata
const Therror = require('therror');
class NotFoundError extends Therror.WithMessage(
'The user ${user} does not exists'
) {}
let error = new UserNotFoundError({ user: 'John' });
let error2 = new UserNotFoundError(error, { user: 'Sarah' });
Custom HTTP Errors
Be expressive with your Server errors
const Therror = require('therror');
class UserNotFound extends Therror.HTTP('404') {}
let err = new UserNotFound('The user ${user} does not exists', {
user: 'Sarah'
});
res.statusCode(err.statusCode);
res.json(err.toPayload());
class DatabaseError extends Therror.HTTP('503') {}
let err = new DatabaseError(cause, 'BD Misconfigured');
console.log(err);
res.statusCode(err.statusCode);
res.json(err.toPayload());
Serializing your errors
For easy logging and server returning using serr.
const Therror = require('therror');
class FatalError extends Therror.Serializable() {}
let cause = new Error('ENOENT');
let error = new FatalError(cause, 'Something went wrong');
console.log('%s', error);
console.log('%j', error);
You can also use logops, an error friendly logger that incorporates support off the shell for this functionality.
Notifications
Never miss again a log trace when creating Errors
const Therror = require('therror');
Therror.on('create', console.error);
class FatalError extends Therror.Notificator() {}
let fatal = new FatalError('This is immediately logged');
Logging levels
Cause not all errors have the same severity. Preconfigure them with it
const Therror = require('therror');
Therror.Loggable.logger = require('logops');
class NotFoundError extends Therror.Loggable('info') {}
let notFound = new NotFoundError('User Not found');
notFound.log();
notFound.level();
Namespacing your errors
For easy identification in logs and tests using err.name
const Therror = require('therror');
class InvalidParamError extends Therror.Namespaced('Server') {}
let err = new InvalidParamError('Not a valid parameter');
console.log(err);
Change the template library
Therror ships lodash template system to allow you adding runtime variables to the final error message.
More info: Therror.parse()
Peer Projects
LICENSE
Copyright 2014,2015,2016 Telefónica I+D
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.