AceDevHub
Intermediate Node.js Interview QuestionsIntermediateConcept

Node.js · Question 62

What are Node.js error handling best practices?

Direct answer

Distinguish operational errors (expected, handle and respond) from programmer errors (fix code); use try/catch in async handlers, centralized error middleware, structured logs with request IDs, and never leak stack traces to clients in production.

Production APIs need a consistent error contract — AceDevHub uses structured API envelopes so web clients show safe messages while logs retain detail.

Why interviewers ask

  1. Operational — validation fail, 404, DB timeout → return 4xx/5xx, retry if idempotent.
  2. Programmer — null reference, logic bug → fix deploy; may crash process after log.
  3. Custom errors — class AppError extends Error { statusCode, code }.
  4. Central handler — Fastify setErrorHandler; Express 4-arg middleware last.
error-handler.mjs
class AppError extends Error {
  constructor(message, statusCode = 500, code = "INTERNAL") {
    super(message);
    this.statusCode = statusCode;
    this.code = code;
  }
}

fastify.setErrorHandler((err, req, reply) => {
  const status = err.statusCode ?? 500;
  req.log.error({ err, reqId: req.id }, err.message);

  reply.status(status).send({
    error: {
      code: err.code ?? "INTERNAL",
      message: status < 500 ? err.message : "Internal Server Error",
    },
  });
});