Market LiveNIFTY25,263.8-0.14%SENSEX82,192.3+0.34%Gold 24K ₹12,098.38/g down302.9Silver ₹146.46/g down5.43
InsightforGeeks
NodeJS

Node.js Error Handling in Express: Async Errors, Middleware and Logging

insightforgeeks-editorial
16 Nov 2026
4 min read
Share:

A server that crashes on the first bad request is not ready for production. Good error handling in Express means catching errors in one place, sending a clear response and logging enough detail to fix the problem. This guide uses Express 4.

The error-handling middleware

Express recognises a function with four arguments as an error handler. Register it after all your routes.

app.use((err, req, res, next) => {
  console.error(err);
  const status = err.status || 500;
  res.status(status).json({
    error: status === 500 ? 'Something went wrong' : err.message,
  });
});

Never send the stack trace or internal messages to the client for 500 errors. Log them on the server instead.

Async routes: the common trap

In Express 4, an error thrown inside an async handler is not caught automatically. The request hangs or the process emits an unhandled rejection. Wrap async handlers so rejections reach next.

const wrap = (fn) => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next);

app.get('/users/:id', wrap(async (req, res) => {
  const user = await User.findById(req.params.id);
  if (!user) {
    const err = new Error('User not found');
    err.status = 404;
    throw err;
  }
  res.json(user);
}));

Express 5 handles rejected promises from async handlers itself, so the wrapper is not needed there.

Use your own error class

class HttpError extends Error {
  constructor(status, message) {
    super(message);
    this.status = status;
  }
}
// throw new HttpError(400, 'Email is required');

Handle 404s

app.use((req, res) => res.status(404).json({ error: 'Not found' }));

Place this after your routes but before the error handler.

Process-level safety nets

process.on('unhandledRejection', (reason) => {
  console.error('Unhandled rejection', reason);
});
process.on('uncaughtException', (err) => {
  console.error('Uncaught exception', err);
  process.exit(1);
});

After an uncaught exception the process state is unreliable. Log it and exit, and let a process manager such as pm2 or systemd restart the app.

Logging

  • Log the request method, path, status and a request ID with each error.
  • Use a structured logger such as pino or winston instead of plain console.log.
  • Never log passwords, tokens or full card numbers.

Validate input early

Many errors come from bad input. Validate bodies and parameters with a library such as express-validator or zod and return 400 with a clear message before touching the database.

Operational and programmer errors

It helps to separate two kinds of errors. Operational errors are expected problems at run time: a user sends invalid input, a database is unreachable, a request times out. You handle these and respond with a proper status code. Programmer errors are bugs, such as reading a property of undefined. You cannot recover sensibly from them; log them, fix them and let the process restart.

Choose the right status codes

  • 400 for invalid input, 401 when authentication is missing, 403 when it is not allowed.
  • 404 when the resource does not exist, 409 for conflicts such as a duplicate email.
  • 422 if you prefer it for validation failures.
  • 429 when rate limits are exceeded.
  • 500 for unexpected server errors, and 503 when a dependency is down.

A consistent error response

Clients find your API easier to use when every error has the same shape, for example:

{
  "error": {
    "code": "VALIDATION_FAILED",
    "message": "Email is required",
    "requestId": "b7c1f2"
  }
}

A request ID in both the response and your logs lets you find the exact failure when a user reports a problem.

Graceful shutdown

const server = app.listen(PORT);
process.on('SIGTERM', () => {
  server.close(() => {
    mongoose.connection.close(false).then(() => process.exit(0));
  });
});

Process managers send SIGTERM when they restart your app. Closing the server lets in-flight requests finish before the process exits, which avoids dropped requests during deployments.

Database and external calls

  • Set timeouts on HTTP and database calls so that a slow dependency cannot hang requests forever.
  • Retry only idempotent operations, and with a delay that grows each time.
  • Handle the "connection lost" case and reconnect rather than crash.
  • Do not leak internal details such as SQL or stack traces in responses.

Testing your error paths

Write tests for the failure cases, not just the successful ones: missing fields, wrong types, nonexistent IDs and failing dependencies. Libraries such as supertest let you call your Express app without opening a port and check the status code and body for each case.

Tags:#nodejs#express#error handling
Found this helpful? Share it with friends & colleagues
Share:
insightforgeeks-editorial Verified Editorial Staff

Covering financial markets, commodity rates, and practical technology insights for India. Researched and fact-checked in accordance with our Editorial Policy.

Published on 16 November 2026General Information · Disclaimer

Recommended based on your reading interest

More in NodeJS