2.0.1 • Published 1 month ago
@kamalyb/errors v2.0.1
errors
solely for personal need instead of repeating in every project
example
import express, { Express } from "express";
import {
BadRequestError,
ForbiddenError,
InternalServerError,
NotAuthorizedError,
NotFoundError,
RateLimitError,
ValidationError,
ValidatorValidationError,
CustomError,
} from "@kamalyb/errors";
type ErrorType =
| "BadRequest"
| "Forbidden"
| "InternalServer"
| "NotAuthorized"
| "NotFound"
| "RateLimit"
| "Validation"
| "ValidatorValidation";
const app: Express = express();
app.get("/throw", (req, res) => {
const type: ErrorType = req.body.type;
switch (type) {
case "BadRequest":
/**
* @param string | { message: string, field?: string } | string[] | { message: string, field?: string }[]
* @required true
* @status 400
*/
throw new BadRequestError({ message: "invalid data" });
case "Forbidden":
/**
* @param string
* @required false
* @default "thou shalt not"
* @status 403
*/
throw new ForbiddenError();
case "InternalServer":
/**
* @status 500
*/
throw new InternalServerError();
case "NotAuthorized":
/**
* @param string | { message: string, field?: string }
* @required false
* @default "you shall not pass"
* @status 401
*/
throw new NotAuthorizedError();
case "NotFound":
/**
* @param string | { message: string, field?: string } | string[] | { message: string, field?: string }[]
* @required true
* @status 404
*/
throw new NotFoundError();
case "RateLimit":
/**
* @param string
* @required false
* @default "too many requests. please try again later"
* @status 429
*/
throw new RateLimitError();
case "Validation":
/**
* @param string | { message: string, field?: string } | string[] | { message: string, field?: string }[]
* @required true
* @status 422
*/
throw new ValidationError();
case "ValidatorValidation":
/**
* @param validationResult(req).array()
* @required true
* @status 422
*/
throw new ValidatorValidationError();
}
});
app.use((error: Error, req: Request, res: Response, next: NextFunction) => {
if (error instanceof CustomError) {
return res.status(error.status).send({ errors: error.serialize() });
// sends { errors: [{ message: "i am error message", field: "i am error field or undefined"}] }
}
res.status(500).send({
errors: [
{
message: "internal server error",
},
],
});
});
app.listen(80);