bad-request-error
BadRequestError is a custom error constructor for HTTP errors (bad parameters, forbidden, unauthorized…).
It takes an error message as first parameter and optionally a HTTP error code as second parameter (defaults to 400
).
Installation
It requires at least Node V6 as it uses JavaScript classes.
npm install --save bad-request-error
Usage
In addition to the native Error
constructor properties, BadRequestError
adds httpStatus
and has its name
property set to BadRequestError
.
const BadRequestError = require('bad-request-error');
async function addComment(req, res) {
await const isCorrectPasswd = checkPasswd(req);
if (!isCorrectPasswd) return throw new BadRequestError('Your password looks wrong', 401);
}
It's very convenient to use it with an error handler function like the following:
function handleError(err, res) {
if (res && err.name && err.name === 'BadRequestError') {
res.status(err.httpStatus).json({ error: err.message });
return;
}
if (res) res.status(500).send('Server Error');
console.error(err);
}
module.exports = handleError;
If using promises, the error is easily handled in a catch block.
const BadRequestError = require('bad-request-error');
const handleError = require('/lib/handleError');
function checkPasswd(passwd) {}
function addComment(req, res) {
checkPasswd(req.body.passwd)
.then(() => {
})
.catch(err => handleError(err, res));
}
Contributing
There's sure room for improvement, so feel free to hack around and submit PRs!
Please just follow the style of the existing code, which is Airbnb's style with minor modifications.
To maintain things clear and visual, please follow the git commit template.