Notes/src/routes/error_handlers.ts

40 lines
1.2 KiB
TypeScript
Raw Normal View History

import type { Application, NextFunction, Request, Response } from "express";
import log from "../services/log.js";
import NotFoundError from "../errors/not_found_error.js";
import ForbiddenError from "../errors/forbidden_error.js";
2023-05-07 15:23:46 +02:00
function register(app: Application) {
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
2025-01-09 18:07:02 +02:00
if (err.code !== "EBADCSRFTOKEN") {
2023-05-07 15:23:46 +02:00
return next(err);
}
2025-01-09 18:07:02 +02:00
log.error(`Invalid CSRF token: ${req.headers["x-csrf-token"]}, secret: ${req.cookies["_csrf"]}`);
next(new ForbiddenError("Invalid CSRF token"));
2023-05-07 15:23:46 +02:00
});
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new NotFoundError(`Router not found for request ${req.method} ${req.url}`);
2023-05-07 15:23:46 +02:00
next(err);
});
// error handler
2025-03-06 23:21:47 +01:00
app.use((err: any, req: Request, res: Response, _next: NextFunction) => {
if (err.status !== 404) {
2023-05-07 15:23:46 +02:00
log.info(err);
} else {
log.info(`${err.status} ${req.method} ${req.url}`);
2023-05-07 15:23:46 +02:00
}
res.status(err.status || 500);
res.send({
message: err.message
});
});
}
export default {
2023-05-07 15:23:46 +02:00
register
};