What I want to do is to create a customized Error that contains some extra properties over the built-in Error. For instance, to handle an inexsitent url/endpoint, I implemented the middleware as
const app = express();
//... skip some imports and basic middlewares
app.use("/api/v1/events", eventRouter);
app.use("/api/v1/users", userRouter);
interface IError extends Error {
status: string;
statusCode: number;
}
app.all("*", (req: Request, res: Response, next: NextFunction) => {
const err = new Error(`Can't find ${req.originalUrl}.`);
(err as any).status = "fail";
(err as any).statusCode = 404;
next(err);
});
app.use((err: IError, req: Request, res: Response, next: NextFunction) => {
err.statusCode = err.statusCode || 500;
err.name;
err.status = err.status || "error";
res.status(err.statusCode).json({
status: err.status,
message: err.message,
});
});
I had to cast err to type any because it would raise an error when I added the properties status and statusCode to err since type Error doesn't include these two properties. I am not sure if this is a good practice because I know it is not recommanded to declare or cast a variable to any, which actually is against the purpose of TypeScipt.
Are there any better solutions to it?
I had to cast err to type any because it would raise an error when I added the properties status and statusCode to err since type Error doesn't include these two properties. I am not sure if this is a good practice because I know it is not recommanded to declare or cast a variable to any, which actually is against the purpose of TypeScipt.
Are there any better solutions to it?
0 comments:
Post a Comment
Thanks