An HTTP Error collection to use in your next REST API.
npm install --save throw.js
or
yarn add throw.js
const express = require("express");
const app = express();
const { NotFound } = require("throw.js");
const logger = require("winston");
app.get("/", (req, res, next) => {
next(new NotFound());
});
app.use((err, req, res, next) => {
logger.error(err);
if (req.app.get("env") !== "development" && req.app.get("env") !== "test") {
delete err.stack;
}
res.status(err.statusCode || 500).json(err);
});
app.listen(3000);
const { CustomError } = require("throw.js");
throw new CustomError(message, statusCode?, errorCode?, originalError?);
Parameters:
- message[optional]: Detailed message of this error
- statusCode[optional]: The HTTP Status number to return
- errorCode[optional]: An internal unique code identifier of this error
const { CustomError } = require("throw.js");
try {
// throws an error
} catch (e) {
// Pass the error as a parameter to keep its original stack trace
throw new CustomError(message, statusCode, errorCode, e);
}
All of the classes below have all parameters set up by default, based on RFC7231.
But you can override the message
and the errorCode
to fit your for personal needs.
BadRequest(message?, errorCode?, originalError?);
Unauthorized(message?, errorCode?, originalError?);
PaymentRequired(message?, errorCode?, originalError?);
Forbidden(message?, errorCode?, originalError?);
NotFound(message?, errorCode?, originalError?);
MethodNotAllowed(message?, errorCode?, originalError?);
NotAcceptable(message?, errorCode?, originalError?);
ProxyAuthenticationRequired(message?, errorCode?, originalError?);
RequestTimeout(message?, errorCode?, originalError?);
Conflict(message?, errorCode?, originalError?);
Gone(message?, errorCode?, originalError?);
UnprocessableEntity(message?, errorCode?, originalError?);
FailedDependency(message?, errorCode?, originalError?);
InternalServerError(message?, errorCode?, originalError?);
NotImplemented(message?, errorCode?, originalError?);
BadGateway(message?, errorCode?, originalError?);
ServiceUnavailable(message?, errorCode?, originalError?);
GatewayTimeout(message?, errorCode?, originalError?);
HttpVersionNotSupported(message?, errorCode?, originalError?);
NetworkAuthenticationRequired(message?, errorCode?, originalError?);
- Implement more Error Classes