Server side error handling service, best suited for promise chains, uses http-errors
.
const error = require('http-errors-promise');
router.get('/', function(req, res, next) {
getStuffFromDB()
.then(//...)
.catch(function (error) {
return error.respond(
res,
error, // error from the call 'getStuffFromDB'
'Something went wrong' // error from this context
);
});
});
function doSomething() {
// returns a promise
return new Promise((resolve, reject) => {
// doing some stuff...
if (someCondition) {
resolve(result);
} else {
return error(null, 'messed up while doing something', 500);
}
})
}
function doSomethingElse() {
// calls 'doSomething', does its own processing and returns a promise
return doSomething()
.then(result => {
// does some stuff
return newResult;
})
.catch(err => error(
err,
'Messed up while doing somethingElse'
));
}
function mainFunction() {
doSomethingElse()
.catch(err => {
// here 'err' could either be from 'doSomething' or
// 'doSomethingElse' based on what went wrong and where
// the error actually originated from, more technically the
// error properly bubbles up
})
}
err
error object recieved from a function callsecErr
error from the current contextstatus
http status, defaults to 500- returns a rejected promise with the resulting error
dontReject
returns the resulting error instead of a rejected promise
- similar to
error
method, except that it takes the express' response object and sends the response with the error instead of returning
- creates and returns an error using
http-errors
- creates and returns commonly seen errors by using a dynamically set
modelName
in the error message, also usinghttp-errors
- the common errors are defined in
common.js
(you're welcome to add new errors there)
Design inspired by ralusek's work on error handling