MyInternships.in

Express.js & REST APIs

Node.js Express Error Handling

Express error-handling middleware is identified by having four parameters. Registered last, it catches errors passed to next() and, in Express 5, errors thrown from async handlers too.


What is Express Error Handling in Node.js?

Express error-handling middleware is identified by having four parameters. Registered last, it catches errors passed to next() and, in Express 5, errors thrown from async handlers too.

Express Error Handling example

Centralised error handling
JavaScript
class AppError extends Error {
  constructor(message, statusCode = 500) {
    super(message);
    this.statusCode = statusCode;
  }
}

app.get('/api/jobs/:id', async (req, res, next) => {
  const job = await Job.findById(req.params.id);
  if (!job) return next(new AppError('Job not found', 404));
  res.json(job);
});

// 404 for anything unmatched
app.use((req, res) => res.status(404).json({ error: 'Route not found' }));

// error handler — four parameters, registered LAST
app.use((err, req, res, next) => {
  const status = err.statusCode ?? 500;
  logger.error({ err, url: req.originalUrl });
  res.status(status).json({
    error: status === 500 ? 'Internal server error' : err.message,
  });
});

How this works

Generic messages are returned for 500s so stack traces and internal details never reach a client, while the real error is logged server-side.

Key points to remember

  • Express 4 needs a wrapper to forward async errors; Express 5 handles them natively.
  • Never send err.stack to the client in production.
  • One error handler keeps error responses consistent across the whole API.

Common mistakes with Express Error Handling

  • A three-parameter function used as an error handler — Express treats it as normal middleware.
  • Registering the error handler before the routes.

Node.js Express Error Handling— Interview Questions & FAQs

How do I handle async errors in Express?+

In Express 5 a rejected promise from a handler goes to the error middleware automatically. In Express 4, wrap handlers in a helper such as fn => (req,res,next) => Promise.resolve(fn(req,res,next)).catch(next).

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships