From f064951b521854ba89b30fc580dd2d3507e42014 Mon Sep 17 00:00:00 2001 From: ~Chiluka Akshitha <120377576+AKSHITHA-CHILUKA@users.noreply.github.com> Date: Wed, 31 Jul 2024 08:54:34 +0530 Subject: [PATCH] Create errorHandlers.js errorHandlers.js file that includes handling for general errors, 404 not found, and custom errors. This version includes environment-based logging to differentiate between development and production modes --- server/routes/errorHandlers.js | 54 ++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 server/routes/errorHandlers.js diff --git a/server/routes/errorHandlers.js b/server/routes/errorHandlers.js new file mode 100644 index 0000000..a01cb47 --- /dev/null +++ b/server/routes/errorHandlers.js @@ -0,0 +1,54 @@ +// errorHandlers.js + +// General error handler +function generalErrorHandler(err, req, res, next) { + if (process.env.NODE_ENV === 'development') { + // Detailed error info for development + console.error(err.stack); + res.status(500).json({ + success: false, + message: err.message, + stack: err.stack + }); + } else { + // Generic error message for production + console.error(err.stack); // Still log error details for debugging purposes + res.status(500).json({ + success: false, + message: 'Something went wrong!' + }); + } +} + +// 404 Not Found handler +function notFoundHandler(req, res, next) { + res.status(404).json({ + success: false, + message: 'Resource not found' + }); +} + +// Custom error handler for different types of errors +function customErrorHandler(err, req, res, next) { + if (err.name === 'ValidationError') { + return res.status(400).json({ + success: false, + message: 'Invalid input', + details: err.details + }); + } + if (err.name === 'UnauthorizedError') { + return res.status(401).json({ + success: false, + message: 'Unauthorized access' + }); + } + // Pass any other errors to the general error handler + next(err); +} + +module.exports = { + generalErrorHandler, + notFoundHandler, + customErrorHandler +};