Implemented error handling middleware

This commit is contained in:
Alex Holliday committed 2024-05-27 10:47:14 -07:00
1 parent 992ff5024c
commit 950222f94e
6 files changed
+106 -92

No files matched your search

+16 -19
View File
@@ -21,35 +21,32 @@ const issueToken = (payload) => {
* @param {express.Response} res * @param {express.Response} res
* @returns {{success: Boolean, msg: String}} * @returns {{success: Boolean, msg: String}}
*/ */
const registerController = async (req, res) => { const registerController = async (req, res, next) => {
// joi validation // joi validation
try { try {
await registerValidation.validateAsync(req.body); await registerValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
return res error.status = 400;
.status(400) error.service = SERVICE_NAME;
.json({ success: false, msg: error.details[0].message }); error.message = error.details[0].message;
next(error);
return;
} }
// Check if the user exists // Check if the user exists
try { try {
const isUser = await req.db.getUserByEmail(req, res); const isUser = await req.db.getUserByEmail(req, res);
if (isUser) { if (isUser) {
logger.error("User already exists", { throw new Error("User already exists");
service: SERVICE_NAME,
userId: isUser._id,
});
return res
.status(400)
.json({ success: false, msg: "User already exists" });
} }
} catch (error) { } catch (error) {
logger.error(error.message, { service: SERVICE_NAME }); error.service = SERVICE_NAME;
return res.status(500).json({ success: false, msg: error.message }); next(error);
return;
} }
// Create a new user
try { try {
// Create a new user
const newUser = await req.db.insertUser(req, res); const newUser = await req.db.insertUser(req, res);
// TODO: Send an email to user // TODO: Send an email to user
// Will add this later // Will add this later
@@ -63,8 +60,8 @@ const registerController = async (req, res) => {
.status(200) .status(200)
.json({ success: true, msg: "User created", data: token }); .json({ success: true, msg: "User created", data: token });
} catch (error) { } catch (error) {
logger.error(error.message, { service: SERVICE_NAME }); error.service = SERVICE_NAME;
return res.status(500).json({ success: false, msg: error.message }); next(error);
} }
}; };
@@ -76,7 +73,7 @@ const registerController = async (req, res) => {
* @returns {Promise<Express.Response>} * @returns {Promise<Express.Response>}
* @throws {Error} * @throws {Error}
*/ */
const loginController = async (req, res) => { const loginController = async (req, res, next) => {
try { try {
// Validate input // Validate input
await loginValidation.validateAsync(req.body); await loginValidation.validateAsync(req.body);
@@ -104,9 +101,9 @@ const loginController = async (req, res) => {
.status(200) .status(200)
.json({ success: true, msg: "Found user", data: token }); .json({ success: true, msg: "Found user", data: token });
} catch (error) { } catch (error) {
error.status = 500;
// Anything else should be an error // Anything else should be an error
logger.error(error.message, { service: SERVICE_NAME }); next(error);
return res.status(500).json({ success: false, msg: error.message });
} }
}; };
+58 -52
View File
@@ -4,7 +4,6 @@ const {
monitorValidation, monitorValidation,
} = require("../validation/joi"); } = require("../validation/joi");
const logger = require("../utils/logger");
const SERVICE_NAME = "monitorController"; const SERVICE_NAME = "monitorController";
/** /**
@@ -15,13 +14,13 @@ const SERVICE_NAME = "monitorController";
* @returns {Promise<Express.Response>} * @returns {Promise<Express.Response>}
* @throws {Error} * @throws {Error}
*/ */
const getAllMonitors = async (req, res) => { const getAllMonitors = async (req, res, next) => {
try { try {
const monitors = await req.db.getAllMonitors(); const monitors = await req.db.getAllMonitors();
return res.json({ success: true, msg: "Monitors found", data: monitors }); return res.json({ success: true, msg: "Monitors found", data: monitors });
} catch (error) { } catch (error) {
logger.error(error.message, { service: SERVICE_NAME }); error.service = SERVICE_NAME;
return res.status(500).json({ success: false, msg: error.message }); next(error);
} }
}; };
@@ -33,25 +32,28 @@ const getAllMonitors = async (req, res) => {
* @returns {Promise<Express.Response>} * @returns {Promise<Express.Response>}
* @throws {Error} * @throws {Error}
*/ */
const getMonitorById = async (req, res) => { const getMonitorById = async (req, res, next) => {
const { error } = getMonitorByIdValidation.validate(req.params); try {
if (error) { await getMonitorByIdValidation.validateAsync(req.params);
return res } catch (error) {
.status(422) error.status = 422;
.json({ success: false, msg: error.details[0].message }); error.message = error.details[0].message;
next(error);
return;
} }
try { try {
const monitor = await req.db.getMonitorById(req, res); const monitor = await req.db.getMonitorById(req, res);
if (!monitor) { if (!monitor) {
logger.error("Monitor not found", { service: SERVICE_NAME }); const error = new Error("Monitor not found");
return res.status(404).json({ success: false, msg: "Monitor not found" }); error.status = 404;
throw error;
} }
return res.json({ success: true, msg: "Monitor found", data: monitor }); return res.json({ success: true, msg: "Monitor found", data: monitor });
} catch (error) { } catch (error) {
logger.error(error.message, { service: SERVICE_NAME }); error.service = SERVICE_NAME;
return res.status(500).json({ success: false, msg: error.message }); next(error);
} }
}; };
@@ -63,7 +65,7 @@ const getMonitorById = async (req, res) => {
* @returns {Promise<Express.Response>} * @returns {Promise<Express.Response>}
* @throws {Error} * @throws {Error}
*/ */
const getMonitorsByUserId = async (req, res) => { const getMonitorsByUserId = async (req, res, next) => {
const { error } = getMonitorsByUserIdValidation.validate(req.params); const { error } = getMonitorsByUserIdValidation.validate(req.params);
if (error) { if (error) {
return res return res
@@ -76,9 +78,9 @@ const getMonitorsByUserId = async (req, res) => {
const monitors = await req.db.getMonitorsByUserId(req, res); const monitors = await req.db.getMonitorsByUserId(req, res);
if (monitors && monitors.length === 0) { if (monitors && monitors.length === 0) {
return res const err = new Error("No monitors found");
.status(404) err.status = 404;
.json({ success: false, msg: "No monitors not found" }); throw err;
} }
return res.json({ return res.json({
@@ -87,8 +89,8 @@ const getMonitorsByUserId = async (req, res) => {
data: monitors, data: monitors,
}); });
} catch (error) { } catch (error) {
logger.error(error.message, { service: SERVICE_NAME }); error.service = SERVICE_NAME;
return res.status(500).json({ success: false, msg: error.message }); next(error);
} }
}; };
@@ -101,12 +103,15 @@ const getMonitorsByUserId = async (req, res) => {
* @throws {Error} * @throws {Error}
*/ */
const createMonitor = async (req, res) => { const createMonitor = async (req, res, next) => {
const { error } = monitorValidation.validate(req.body); try {
if (error) { await monitorValidation.validateAsync(req.body);
return res } catch (error) {
.status(422) error.status = 422;
.json({ success: false, msg: error.details[0].message }); error.service = SERVICE_NAME;
error.message = error.details[0].message;
next(error);
return;
} }
try { try {
@@ -115,8 +120,8 @@ const createMonitor = async (req, res) => {
.status(201) .status(201)
.json({ success: true, msg: "Monitor created", data: monitor }); .json({ success: true, msg: "Monitor created", data: monitor });
} catch (error) { } catch (error) {
logger.error(error.message, { service: SERVICE_NAME }); error.service = SERVICE_NAME;
return res.status(500).json({ success: false, msg: error.message }); next(error);
} }
}; };
@@ -129,15 +134,19 @@ const createMonitor = async (req, res) => {
* @throws {Error} * @throws {Error}
*/ */
const deleteMonitor = async (req, res) => { const deleteMonitor = async (req, res, next) => {
const { error } = getMonitorByIdValidation.validate(req.params);
if (error) {
return res
.status(422)
.json({ success: false, msg: error.details[0].message });
}
try { try {
const monitor = await req.db.deleteMonitor(req, res); await getMonitorByIdValidation.validateAsync(req.params);
} catch (error) {
error.status = 422;
error.service = SERVICE_NAME;
error.message = error.details[0].message;
next(error);
return;
}
try {
const monitor = await req.db.deleteMonitor(req, res, next);
/** /**
* TODO * TODO
* We should remove all checks and alerts associated with this monitor * We should remove all checks and alerts associated with this monitor
@@ -146,8 +155,8 @@ const deleteMonitor = async (req, res) => {
*/ */
return res.status(200).json({ success: true, msg: "Monitor deleted" }); return res.status(200).json({ success: true, msg: "Monitor deleted" });
} catch (error) { } catch (error) {
logger.error(error.message, { service: SERVICE_NAME }); error.service = SERVICE_NAME;
return res.status(500).json({ success: false, msg: error.message }); next(error);
} }
}; };
@@ -160,18 +169,15 @@ const deleteMonitor = async (req, res) => {
* @throws {Error} * @throws {Error}
*/ */
const editMonitor = async (req, res, next) => { const editMonitor = async (req, res, next) => {
let { paramError } = getMonitorByIdValidation.validate(req.params); try {
if (paramError) { await getMonitorByIdValidation.validateAsync(req.params);
return res await monitorValidation.validateAsync(req.body);
.status(422) } catch (error) {
.json({ success: false, msg: paramError.error.details[0].message }); error.status = 422;
} error.service = SERVICE_NAME;
error.message = error.details[0].message;
let { error } = monitorValidation.validate(req.body); next(error);
if (error) { return;
return res
.status(422)
.json({ success: false, msg: error.details[0].message });
} }
try { try {
@@ -180,8 +186,8 @@ const editMonitor = async (req, res, next) => {
.status(200) .status(200)
.json({ success: true, msg: "Monitor edited", data: editedMonitor }); .json({ success: true, msg: "Monitor edited", data: editedMonitor });
} catch (error) { } catch (error) {
logger.error(error.message, { service: SERVICE_NAME }); error.service = SERVICE_NAME;
return res.status(500).json({ success: false, msg: error.message }); next(error);
} }
}; };
+7
View File
@@ -7,6 +7,7 @@ const { connectDbAndRunServer } = require("./configs/db");
require("dotenv").config(); require("dotenv").config();
const logger = require("./utils/logger"); const logger = require("./utils/logger");
const { verifyJWT } = require("./middleware/verifyJWT"); const { verifyJWT } = require("./middleware/verifyJWT");
const { handleErrors } = require("./middleware/handleErrors");
// const { sendEmail } = require('./utils/sendEmail') // const { sendEmail } = require('./utils/sendEmail')
@@ -62,6 +63,12 @@ app.use((req, res, next) => {
app.use("/api/v1/auth", authRouter); app.use("/api/v1/auth", authRouter);
app.use("/api/v1/monitors", verifyJWT, monitorRouter); app.use("/api/v1/monitors", verifyJWT, monitorRouter);
/**
* Error handler middleware
* MUST be called after all routes
*/
app.use(handleErrors);
// Testing email service // Testing email service
// app.use('/sendEmail', async (req, res) => { // app.use('/sendEmail', async (req, res) => {
// const response = sendEmail(['veysel.boybay@bluewavelabs.ca'], 'Testing email service', '<h1>Testing Bluewavelabs</h1>'); // const response = sendEmail(['veysel.boybay@bluewavelabs.ca'], 'Testing email service', '<h1>Testing Bluewavelabs</h1>');
+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"]; const token = req.headers["authorization"];
// Make sure a token is provided // Make sure a token is provided
if (!token) { if (!token) {
logger.error("No token provided", { service: SERVICE_NAME }); const error = new Error("No token provided");
return res.status(401).json({ success: false, msg: "No token provided" }); error.status = 401;
error.service = SERVICE_NAME;
next(error);
return;
} }
// Make sure it is properly formatted // Make sure it is properly formatted
if (token.startsWith(TOKEN_PREFIX)) { if (token.startsWith(TOKEN_PREFIX)) {
@@ -32,10 +35,9 @@ const verifyJWT = (req, res, next) => {
next(); next();
}); });
} else { } else {
logger.error("Invalid token format", { service: SERVICE_NAME }); error.status = 400;
return res error.service = SERVICE_NAME;
.status(400) next(error);
.json({ success: false, msg: "Invalid token format" });
} }
}; };
+8 -15
View File
@@ -12,28 +12,21 @@ const verifyOwnership = (Model, paramName) => {
logger.error("Document not found", { logger.error("Document not found", {
service: SERVICE_NAME, service: SERVICE_NAME,
}); });
return res const error = new Error("Document not found");
.status(404) error.status = 404;
.json({ success: false, msg: "Document not found" }); throw error;
} }
// If the userID does not match the document's userID, return a 403 error // If the userID does not match the document's userID, return a 403 error
if (userId.toString() !== doc.userId.toString()) { if (userId.toString() !== doc.userId.toString()) {
logger.error("Unauthorized access", { const error = new Error("Unauthorized access");
service: SERVICE_NAME, error.status = 403;
}); throw error;
return res.status(403).json({
success: false,
msg: "You are not authorized to perform this action",
});
} }
next(); next();
} catch (error) { } catch (error) {
logger.error(error.message, { error.service = SERVICE_NAME;
service: SERVICE_NAME, next(error);
});
return res.status(500).json({ success: false, msg: error.message });
} }
}; };
}; };