Initial commit - Church Music Database
This commit is contained in:
41
new-site/backend/middleware/errorHandler.js
Normal file
41
new-site/backend/middleware/errorHandler.js
Normal file
@@ -0,0 +1,41 @@
|
||||
export const notFound = (req, res, next) => {
|
||||
res.status(404).json({
|
||||
error: "Not Found",
|
||||
message: `Cannot ${req.method} ${req.originalUrl}`,
|
||||
});
|
||||
};
|
||||
|
||||
export const errorHandler = (err, req, res, next) => {
|
||||
console.error("Error:", err);
|
||||
|
||||
// Handle validation errors
|
||||
if (err.name === "ValidationError") {
|
||||
return res.status(400).json({
|
||||
error: "Validation Error",
|
||||
details: err.errors,
|
||||
});
|
||||
}
|
||||
|
||||
// Handle duplicate key errors
|
||||
if (err.code === 11000) {
|
||||
return res.status(400).json({
|
||||
error: "Duplicate Entry",
|
||||
message: "A record with this value already exists",
|
||||
});
|
||||
}
|
||||
|
||||
// Handle JWT errors
|
||||
if (err.name === "JsonWebTokenError") {
|
||||
return res.status(401).json({
|
||||
error: "Invalid Token",
|
||||
message: "Your session is invalid",
|
||||
});
|
||||
}
|
||||
|
||||
// Default error
|
||||
const statusCode = err.statusCode || 500;
|
||||
res.status(statusCode).json({
|
||||
error: err.message || "Internal Server Error",
|
||||
...(process.env.NODE_ENV === "development" && { stack: err.stack }),
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user