mirror of
https://github.com/bluewave-labs/Checkmate.git
synced 2026-05-07 09:09:48 -05:00
Implemented error handling middleware
This commit is contained in:
@@ -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 };
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user