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":
throw new BadRequestError({ message: "invalid data" });
case "Forbidden":
throw new ForbiddenError();
case "InternalServer":
throw new InternalServerError();
case "NotAuthorized":
throw new NotAuthorizedError();
case "NotFound":
throw new NotFoundError();
case "RateLimit":
throw new RateLimitError();
case "Validation":
throw new ValidationError();
case "ValidatorValidation":
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() });
}
res.status(500).send({
errors: [
{
message: "internal server error",
},
],
});
});
app.listen(80);