Code Reference

Error Handling

Node.js · Reference cheat sheet

Error Handling

Node.js · Reference cheat sheet


📋 Overview

Robust Node services distinguish operational errors (expected failures) from programmer bugs, return safe HTTP responses, and log details server-side.

🔧 Core concepts

LayerApproach
Sync throwCaught by try/catch or framework
Async rejectionMust be handled or process warns/crashes
HTTP mappingMap errors → status codes
Process hooksuncaughtException / unhandledRejection (last resort)
StatusTypical meaning
400Bad input
401 / 403Auth / forbidden
404Missing resource
409Conflict
500Unexpected server failure

💡 Examples

Express async wrapper:

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

app.get("/user/:id", wrap(async (req, res) => {
  const user = await db.find(req.params.id);
  if (!user) {
    const err = new Error("Not found");
    err.status = 404;
    throw err;
  }
  res.json(user);
}));

Central error middleware:

app.use((err, req, res, next) => {
  const status = err.status || 500;
  if (status >= 500) console.error(err);
  res.status(status).json({
    error: status >= 500 ? "Internal error" : err.message,
  });
});

Fastify setErrorHandler:

fastify.setErrorHandler((err, req, reply) => {
  reply.status(err.statusCode || 500).send({ error: err.message });
});

⚠️ Pitfalls

  • Leaking stack traces to clients exposes internals.
  • Swallowing errors (catch (e) \{\}) hides outages.
  • uncaughtException handlers that continue serving are unsafe — shut down and restart.

On this page