A javascript error creator for some often used HTTP error
$ npm install some-http-error
You can use this module in any node.js web frameworks, such as express
var HttpError = require('some-http-error');
function handle(req, res, next) {
var userId = req.query.id;
// If some error happened
if (!userId) {
// You can pass it to error handling middleware
next(new HttpError.BadRequestError('"id" is not set'));
// Or just throw it!
// throw new HttpError.BadRequestError('"id" is not set'));
}
// In promise
User.findById(userId).then(user => {
if (!user) {
// Not found, just throw it!
throw new HttpError.NotFoundError('User not found');
}
// ...
// Don't forget to catch the error, and pass it to error handling middleware
}).catch(next);
}
var HttpError = require('some-http-error');
function errorHandle(err, req, res, next) {
if (err instanceof HttpError) {
// If it is an HttpError, send the HTTP status code and error message
res.sendStatus(err.statusCode).json(err.message);
} else {
// Otherwise send 500
res.sendStatus(500).json(err.message);
}
The basic HttpError object constructor, and you can construct HttpError like this:
new HttpError(404)
new HttpError(404, 'This page is not found')
- statusCode:
400
- message:
Bad Request
- statusCode:
401
- message:
Unauthorized
- statusCode:
403
- message:
Forbidden
- statusCode:
404
- message:
Not Found
- statusCode:
405
- message:
Method Not Allowed