Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create errorHandlers.js #468

Merged
merged 1 commit into from
Jul 31, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions server/routes/errorHandlers.js
Original file line number Diff line number Diff line change
@@ -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
};
Loading