-
Notifications
You must be signed in to change notification settings - Fork 151
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
- Loading branch information
1 parent
efae5be
commit f064951
Showing
1 changed file
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
}; |