javascript
API
Express Global Error Handler
Centralized error handling middleware for Express apps with proper error classification, logging, and consistent JSON responses.
Apex Logic
0 copies
javascript
class AppError extends Error {
constructor(message, statusCode, code = 'INTERNAL_ERROR') {
super(message);
this.statusCode = statusCode;
this.code = code;
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
const errorHandler = (err, req, res, next) => {
err.statusCode = err.statusCode || 500;
// Log error (only stack for 500s)
if (err.statusCode >= 500) {
console.error(`[${new Date().toISOString()}] ${err.stack}`);
}
// Mongoose validation error
if (err.name === 'ValidationError') {
const messages = Object.values(err.errors).map(e => e.message);
return res.status(400).json({
success: false,
code: 'VALIDATION_ERROR',
errors: messages
});
}
// Mongoose duplicate key
if (err.code === 11000) {
const field = Object.keys(err.keyValue)[0];
return res.status(409).json({
success: false,
code: 'DUPLICATE_KEY',
message: `${field} already exists`
});
}
res.status(err.statusCode).json({
success: false,
code: err.code || 'INTERNAL_ERROR',
message: err.isOperational ? err.message : 'Something went wrong'
});
};
module.exports = { AppError, errorHandler };