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
- Operational — validation fail, 404, DB timeout → return 4xx/5xx, retry if idempotent.
- Programmer — null reference, logic bug → fix deploy; may crash process after log.
- Custom errors — class AppError extends Error { statusCode, code }.
- 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",
},
});
});