Overview
This node module helps you to create your own errors with your defined error codes and handle them within classes in a proper way.
Features
- Creating errors objects instance of
Error
class from the self-defined error codes - Throw the created error any time with informative error message/code and error stack
- Parse any error to HTTP error codes and messages
- Usage with express middleware
- See custom and informative error messages in the client-side of the REST in development environment
ECMAScript support
ES6 only
Installation
$ npm install errorme
API
Check the JSDoc here.
#Installation
npm install errorme --save
#Usage
You can add your custom errors or use the default errors.
const errors = {
"ValidationError": {
"CODE": 100,
"DEFAULT_MESSAGE": "The provided data is not valid",
"HTTP_CODE": 400
},
"ServiceError": {
"CODE": 101,
"DEFAULT_MESSAGE": "Error happend related to the third party service",
"HTTP_CODE": 500
},
}
let options = { overwrite: true, showLogs: true }
let errorme = require('errorme')(errors, options)
let code = 100, customMessage = "The provided data is invalid";
let err = errorme.getError(code, customMessage)
console.log(err instanceof Error)
let httpErr = err.parseTo('http')
console.log(httpErr.code)
console.log(httpErr.definedCode)
console.log(httpErr.message)
let newHttpErr = errorme.getHttpError(100);
console.log(newHttpErr.code == httpErr.code)
console.log(newHttpErr.message == httpErr.message)
Examples
To understand the real use case it will be better to see it with async module, especially with async/waterfall
let waterfall = require('async/waterfall');
let errorme = require('errorme')();
let someFunction = (params, callback)=>{
waterfall([
(_calllback)=>{
let err;
let data;
if(Math.floor((Math.random() * 5)) == 0){
err = errorme.getError(102, "Our database query unfortunately failed")
}else{
data = "Some data retrieved from database"
}
_calllback(err, data)
},
(data, _calllback)=>{
let err;
if(Math.floor((Math.random() * 5)) == 1){
err = errorme.getError(100, "Data doesn't meet to our criteria")
data = null;
}
_calllback(err, data)
},
(data, _calllback)=>{
let err;
let dataOfExternalService;
if(Math.floor((Math.random() * 5)) == 2){
err = errorme.getError(101);
}else{
dataOfExternalService = "Data from external service";
}
_calllback(err, dataOfExternalService)
},
], (error, data)=>{
callback(error, data);
})
}
someFunction("some paramas", (error, data)=>{
if(error){
console.log('Error occured. Code: ' + error.code + ', message: ' + error.message);
}
if(data){
console.log('Data: ' + data);
}
});
Using with express
let express = require('express');
let app = express();
let errorme = require('errorme')();
errorme.middleware(app);
app.get('/', function (req, res) {
let data = {
foo: "Foo data"
}
let err;
res.errormeSend(err, data);
});
app.listen(3000);
Next features
- Will be ability to add other "error languages"
- Optimization for working with error codes defined by external service providers
License
MIT