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.
Installation
npm install --save therror
Usage
const Therror = ; // Extend Therror to create your own classes {} try // ES6 Template String syntax to have great i18n support. throw '${value} is not valid value for ${id}' value: 12 id: 'offset'; // `value` and `id` are now properties of the thrown error. // { [InvalidParamError: 12 is not valid value for offset] value: 12, id: 'offset' } catch err // Add cause to your errors. You can also use Therror directly throw err `Invalid param ""`); // [Error: Invalid param "offset"]
Create your own errors
const Therror = ; { superprops; // Define the message in the class to not specify it in their instances thismessage = '${value} is not valid value for ${id}'; thisstatusCode = 400; } let err = value: 12 id: 'offset' ;console;// { [InvalidParamError: 12 is not valid value for offset] value: 12, id: 'offset', statusCode: 400 }
Adding error causes
const Therror = ; try throw '3rd Party error'; catch err let catchedError = err 'There was a problem with 3rd Party'; console; // [Error: 3rd Party error]
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 = 'The user ${user} does not exists' user: 'Sarah';// or err = new Therror.ServerError[404]('The user ${user} does not exists', {user: 'Sarah'}) res; // 404res;// {// error: 'NotFound',// message: 'The user Sarah does not exists'// }
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 = 'BD Misconfigured'; // Log the real error data// errors with statusCode < 500 will be logged as info. >= 500 will be logged as 'error'console; // [ServiceUnavailable: BD Misconfigured] // but send a hidden response to the client (Express example)res; // 503res;// {// error: 'ServiceUnavailable',// message: 'Service Unavailable'// }
Create your own
{} let error = 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 = ; // Will be parsed by `therror-doc` and store the message for you in a JSON, ready for use your own i18n library (WIP) { superprops; thismessage = '${value} is not valid value for ${id}'; } try throw value: 12 id: 'offset' ; catch err //i18n is your prefered library //err.name === InvalidParamError errmessage = ; // return 'El parámetro ${id} no admite como valor ${value}'; console; // [InvalidParamError: El parámetro offset no admite como valor 12]
Bluebird ready
const Therror = ;const Promise = ; {} Promise;
using mixins
Add functionality to your errors byShared messages across all instances
DRY. Rehuse the errors customizing only metadata
const Therror = ; {} let error = user: 'John' ; // { [UserNotFoundError: The user John does not exists] } let error2 = error user: 'Sarah' ; // { [UserNotFoundError: The user Sarah does not exists] }
Custom HTTP Errors
Be expressive with your Server errors
const Therror = ; {} let err = 'The user ${user} does not exists' user: 'Sarah'; // Send the response (Express example)res; // 404res;// {// error: 'UserNotFound',// message: 'The user Sarah does not exists'// } {} let err = cause 'BD Misconfigured'; console; // [DatabaseError: BD Misconfigured] // Send a hidden response to the client (Express example)res; // 503res;// {// error: 'InternalServerError',// message: 'An internal server error occurred'// }
Serializing your errors
For easy logging and server returning using serr.
const Therror = ; // Builtin mixin in therror {} let cause = 'ENOENT';let error = cause 'Something went wrong'; console;// FatalError: Something went wrong// at repl:1:35// ...// Caused by: Error: ENOENT// at repl:1:50// ...console;// {"message":"Something went wrong","name":"FatalError","constructor":"FatalError","causes":[{"message":"ENOENT","name":"Error","constructor":"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 = ; // Subscribe to error creations and log themTherror; {} let fatal = 'This is immediately logged';// [Error: This is immediately logged]// console.log(fatal) Not miss anymore a trace cause you forgot to log it
Logging levels
Cause not all errors have the same severity. Preconfigure them with it
const Therror = ; // Set your favourite logger (defaults to console)TherrorLoggablelogger = ; {} let notFound = 'User Not found'; notFound;// calls logger.info(notFound)// INFO NotFoundError: User Not Found notFound;// info
Namespacing your errors
For easy identification in logs and tests using err.name
const Therror = ; // Builtin mixin in therror {}let err = 'Not a valid parameter'; console;// [Server.InvalidParamError: Not a valid parameter]
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
- therror-connect: Connect/Express error handler
- therror-doc: Documentation parser for therror (WIP)
- serr: Error serializer to Objects and Strings
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.