set error handler

This commit is contained in:
Mr Swift
2024-08-11 18:26:18 +03:30
parent 648acf59aa
commit 9769e2cf63
3 changed files with 85 additions and 0 deletions
+10
View File
@@ -0,0 +1,10 @@
exports.constants = {
VALIDATION_ERROR: 400,
UNAUTHORIZED: 401,
FORBIDOEN: 403,
NOT_FOUND: 404,
SERVER_ERROR: 500,
SITE_UNAUTHORIZED: 422,
TOO_MANY: 429,
Method_Not_Allowed:405
};
+73
View File
@@ -0,0 +1,73 @@
const { constants } = require("./constants");
const errorHandler = (err, req, res, next) => {
const statusCode = res.statusCode ? res.statusCode : 500;
switch (statusCode) {
case constants.VALIDATION_ERROR:
res.status(statusCode).json({
title: "Validation Failed ",
msg: err.message,
stackTrace: err.stack,
});
break;
case constants.Method_Not_Allowed:
res.status(statusCode).json({
title: "Method Not Allowed ",
msg: err.message,
stackTrace: err.stack,
});
break;
case constants.NOT_FOUND:
res.status(statusCode).json({
title: "Not found ",
msg: err.message,
stackTrace: err.stack,
});
break;
case constants.FORBIDOEN:
res.status(statusCode).json({
title: "Forbidoen ",
msg: err.message,
stackTrace: err.stack,
});
break;
case constants.SERVER_ERROR:
res.status(statusCode).json({
title: "Server Error ",
msg: err.message,
stackTrace: err.stack,
});
break;
case constants.UNAUTHORIZED:
res.status(statusCode).json({
title: "Unauthorized ",
msg: err.message,
stackTrace: err.stack,
});
break;
case constants.SITE_UNAUTHORIZED:
res.status(statusCode).json({
title: "Site Unauthorized ",
msg: err.message,
stackTrace: err.stack,
});
break;
case constants.TOO_MANY:
res.status(statusCode).json({
title: "Too many request",
msg: err.message,
stackTrace: err.stack,
});
break;
default:
console.log(err);
res.status(500).json({
title: "Unhandled error",
msg: err.message,
stackTrace: err.stack
});
break;
}
};
module.exports = { name: "errorHandler", run: errorHandler };
+2
View File
@@ -1,5 +1,6 @@
/// / develop environment config
const { isDev, isProduction, DevServerPort } = require('./_env')
const errorHandler = require('./errorHandler')
const wss = require('./WebSocket/wss')
/// / init express app (wrapping all functions into init() to prevent running in development mode by nuxt dev mode)
function init() {
@@ -53,6 +54,7 @@ function init() {
app.use(isDev ? '/api' : '', router)
app.use(errorHandler.run)
return app
}