mirror of
https://github.com/detleph/server.git
synced 2026-09-04 08:36:06 +02:00
Fix: Add winston; And: Add custom error handlers
+ addCustomHandler() + removeCustomHandler()
This commit is contained in:
+2
-1
@@ -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",
|
||||||
|
|||||||
@@ -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,
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user