Back to library
🟢Node.jsjavascriptintermediate

Express Error Handler

Centralized error handling middleware for Express

expresserror-handlingmiddleware

Code

1// Custom error class
2class AppError extends Error {
3  constructor(message, statusCode) {
4    super(message);
5    this.statusCode = statusCode;
6    this.isOperational = true;
7    Error.captureStackTrace(this, this.constructor);
8  }
9}
10
11// Error handling middleware
12const errorHandler = (err, req, res, next) => {
13  err.statusCode = err.statusCode || 500;
14  err.status = err.status || 'error';
15
16  if (process.env.NODE_ENV === 'development') {
17    res.status(err.statusCode).json({
18      status: err.status,
19      error: err,
20      message: err.message,
21      stack: err.stack
22    });
23  } else {
24    // Production
25    if (err.isOperational) {
26      res.status(err.statusCode).json({
27        status: err.status,
28        message: err.message
29      });
30    } else {
31      // Programming or unknown error
32      console.error('ERROR:', err);
33      res.status(500).json({
34        status: 'error',
35        message: 'Something went wrong'
36      });
37    }
38  }
39};
40
41// Usage in Express app
42app.use(errorHandler);
43
44// Throw custom errors
45app.get('/api/user/:id', async (req, res, next) => {
46  try {
47    const user = await User.findById(req.params.id);
48    
49    if (!user) {
50      throw new AppError('User not found', 404);
51    }
52    
53    res.json(user);
54  } catch (err) {
55    next(err);
56  }
57});

Quick Tips

  • Click the "Copy" button to copy the code to your clipboard
  • This code is production-ready and can be used in your projects
  • Check out related snippets below for more examples

Related Snippets

Build Your Own Snippet Library

Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.