Fix: Add winston; And: Add custom error handlers

+ addCustomHandler()
+ removeCustomHandler()
This commit is contained in:
Stephan
2022-04-28 14:39:16 +02:00
parent 9ac4fb8efd
commit 8bf18267d1
2 changed files with 45 additions and 1 deletions
+2 -1
View File
@@ -30,7 +30,8 @@
"express-async-errors": "^3.1.1", "express-async-errors": "^3.1.1",
"jsonwebtoken": "^8.5.1", "jsonwebtoken": "^8.5.1",
"nodemailer": "^6.7.0", "nodemailer": "^6.7.0",
"redis": "^3.1.2" "redis": "^3.1.2",
"winston": "^3.7.2"
}, },
"devDependencies": { "devDependencies": {
"@types/chai": "^4.2.22", "@types/chai": "^4.2.22",
+43
View File
@@ -5,7 +5,34 @@ import logger from "./logger";
const env = process.env.NODE_ENV || "production"; const env = process.env.NODE_ENV || "production";
type ErrorHandler = (err: any, req: Request, res: Response) => boolean;
const customHandlers: ErrorHandler[] = [];
export function addCustomHandler(handler: ErrorHandler) {
customHandlers.push(handler);
}
export function removeCustomHandler(handler: ErrorHandler): Boolean {
const index = customHandlers.findIndex((h) => h === handler);
if (index < 0) {
return false;
}
customHandlers.splice(index);
return true;
}
export default function defaultErrorHandler(err: any, req: Request, res: Response, next: NextFunction) { export default function defaultErrorHandler(err: any, req: Request, res: Response, next: NextFunction) {
for (const handler of customHandlers) {
// Run custom handler
if (handler(err, req, res)) {
return;
}
}
if (ForwardableError.isForwardableError(err)) { if (ForwardableError.isForwardableError(err)) {
return res.status(err.status).json({ return res.status(err.status).json({
type: "error", type: "error",
@@ -36,4 +63,20 @@ export default function defaultErrorHandler(err: any, req: Request, res: Respons
}, },
}); });
} }
logger.error("--- Unhandled error ---");
logger.error(err);
return res.status(err.status).json({
type: "error",
payload: {
message: err.message,
...(env === "development"
? {
notice: "This error was not caught by any handler, please add handling!",
stack: err.stack,
}
: {}),
},
});
} }