Express.js
Beginner
1 min read
Validation Errors and HTTP Status Codes
Example
// middleware/errors.js (expanded status-code handling)
const HTTP_ERRORS = {
400: 'Bad Request',
401: 'Unauthorized',
403: 'Forbidden',
404: 'Not Found',
409: 'Conflict',
422: 'Unprocessable Entity',
429: 'Too Many Requests',
500: 'Internal Server Error',
};
function errorHandler(err, req, res, next) {
// Handle express-validator errors
if (err.type === 'validation') {
return res.status(422).json({ errors: err.details });
}
// Handle known Mongoose/Sequelize duplicate key
if (err.code === 11000 || err.code === 'ER_DUP_ENTRY') {
return res.status(409).json({ error: { message: 'Resource already exists', code: 'CONFLICT' } });
}
const status = err.status || 500;
const message = err.message || HTTP_ERRORS[status] || 'Unknown error';
const level = status >= 500 ? 'error' : 'warn';
console[level](JSON.stringify({
level, status, message,
requestId: req.requestId,
method: req.method,
path: req.path,
stack: process.env.NODE_ENV !== 'production' ? err.stack : undefined,
}));
res.status(status).json({
error: { message: status >= 500 && process.env.NODE_ENV === 'production'
? HTTP_ERRORS[500] : message }
});
}
module.exports = errorHandler;
Related Resources
Express.js Reference
Complete tag & property list
Express.js How-To Guides
Step-by-step practical guides
Express.js Exercises
Practice what you've learned
More in Express.js