Express.js
Beginner
1 min read
Centralised Error Handling Middleware
Example
// middleware/errors.js
class AppError extends Error {
constructor(message, status = 500, code = 'INTERNAL_ERROR') {
super(message);
this.status = status;
this.code = code;
this.isOperational = true;
}
}
// Wrap async route handlers to forward rejections
function asyncHandler(fn) {
return (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
}
// Central error-handling middleware (register LAST)
function errorHandler(err, req, res, next) {
const status = err.status || 500;
const isProd = process.env.NODE_ENV === 'production';
// Always log the full error
console.error(`[${req.method} ${req.path}]`, err);
res.status(status).json({
error: {
message: isProd && status === 500 ? 'Internal server error' : err.message,
code: err.code || 'INTERNAL_ERROR',
...(isProd ? {} : { stack: err.stack }),
},
});
}
// Usage in a route
const express = require('express');
const app = express();
app.use(express.json());
app.get('/users/:id', asyncHandler(async (req, res) => {
if (req.params.id === '0') throw new AppError('User not found', 404, 'NOT_FOUND');
res.json({ id: req.params.id });
}));
app.use(errorHandler); // must be last
app.listen(3000);
module.exports = { AppError, asyncHandler, 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