mirror of
https://github.com/TriliumNext/Notes.git
synced 2025-08-11 02:42:27 +08:00
refactor(error_handlers): use HttpError classes in errorHandler
also gets rid of "any" type :-)
This commit is contained in:
parent
0c8df7f885
commit
76574f0938
@ -2,6 +2,7 @@ import type { Application, NextFunction, Request, Response } from "express";
|
|||||||
import log from "../services/log.js";
|
import log from "../services/log.js";
|
||||||
import NotFoundError from "../errors/not_found_error.js";
|
import NotFoundError from "../errors/not_found_error.js";
|
||||||
import ForbiddenError from "../errors/forbidden_error.js";
|
import ForbiddenError from "../errors/forbidden_error.js";
|
||||||
|
import HttpError from "../errors/http_error.js";
|
||||||
|
|
||||||
function register(app: Application) {
|
function register(app: Application) {
|
||||||
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
|
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
|
||||||
@ -20,17 +21,19 @@ function register(app: Application) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// error handler
|
// error handler
|
||||||
app.use((err: any, req: Request, res: Response, _next: NextFunction) => {
|
app.use((err: unknown | Error, req: Request, res: Response, _next: NextFunction) => {
|
||||||
if (err.status !== 404) {
|
|
||||||
log.info(err);
|
|
||||||
} else {
|
|
||||||
log.info(`${err.status} ${req.method} ${req.url}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
res.status(err.status || 500);
|
const statusCode = (err instanceof HttpError) ? err.statusCode : 500;
|
||||||
res.send({
|
const errMessage = (err instanceof Error && statusCode !== 404)
|
||||||
message: err.message
|
? err
|
||||||
|
: `${statusCode} ${req.method} ${req.url}`;
|
||||||
|
|
||||||
|
log.info(errMessage);
|
||||||
|
|
||||||
|
res.status(statusCode).send({
|
||||||
|
message: err instanceof Error ? err.message : "Unknown Error"
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user