Implemented error handling middleware

This commit is contained in:
Alex Holliday
2024-05-27 10:47:14 -07:00
parent 992ff5024c
commit 950222f94e
6 changed files with 106 additions and 92 deletions
+9
View File
@@ -0,0 +1,9 @@
const logger = require("../utils/logger");
const handleErrors = (error, req, res, next) => {
error.status = error.status ? error.status : 500;
logger.error(error.message, { service: error.service });
res.status(error.status).json({ success: false, msg: error.message });
};
module.exports = { handleErrors };
+8 -6
View File
@@ -15,8 +15,11 @@ const verifyJWT = (req, res, next) => {
const token = req.headers["authorization"];
// Make sure a token is provided
if (!token) {
logger.error("No token provided", { service: SERVICE_NAME });
return res.status(401).json({ success: false, msg: "No token provided" });
const error = new Error("No token provided");
error.status = 401;
error.service = SERVICE_NAME;
next(error);
return;
}
// Make sure it is properly formatted
if (token.startsWith(TOKEN_PREFIX)) {
@@ -32,10 +35,9 @@ const verifyJWT = (req, res, next) => {
next();
});
} else {
logger.error("Invalid token format", { service: SERVICE_NAME });
return res
.status(400)
.json({ success: false, msg: "Invalid token format" });
error.status = 400;
error.service = SERVICE_NAME;
next(error);
}
};
+8 -15
View File
@@ -12,28 +12,21 @@ const verifyOwnership = (Model, paramName) => {
logger.error("Document not found", {
service: SERVICE_NAME,
});
return res
.status(404)
.json({ success: false, msg: "Document not found" });
const error = new Error("Document not found");
error.status = 404;
throw error;
}
// If the userID does not match the document's userID, return a 403 error
if (userId.toString() !== doc.userId.toString()) {
logger.error("Unauthorized access", {
service: SERVICE_NAME,
});
return res.status(403).json({
success: false,
msg: "You are not authorized to perform this action",
});
const error = new Error("Unauthorized access");
error.status = 403;
throw error;
}
next();
} catch (error) {
logger.error(error.message, {
service: SERVICE_NAME,
});
return res.status(500).json({ success: false, msg: error.message });
error.service = SERVICE_NAME;
next(error);
}
};
};