Handling Errors and Exceptions

1. Using Try-Catch Blocks

Example

try {
  const data = JSON.parse(input);
} catch (err) {
  if (err instanceof SyntaxError) return defaultValue;
  throw err;
}

2. Handling Async Errors

PatternNotes
try { await x } catchIdiomatic
.catch(handler)Promise chain
Forgotten awaitBecomes unhandled rejection

3. Creating Custom Errors

Example

class HttpError extends Error {
  constructor(status, message, opts) {
    super(message, opts);
    this.name = "HttpError";
    this.status = status;
  }
}
throw new HttpError(404, "user not found", { cause: dbErr });
Note: { cause } chains errors v16.9+; visible in stack output.

4. Using Error Stack Traces (error.stack)

PropertyUse
error.stackString trace
Error.stackTraceLimit = 50Increase frames captured
--stack-trace-limit=NCLI equivalent

5. Using Error Codes (error.code)

CodeDomain
ENOENTFile not found
EACCESPermission denied
EADDRINUSEPort in use
ECONNREFUSEDConnection refused
ERR_INVALID_ARG_TYPEBad argument

6. Using Error.captureStackTrace

Example

class AppError extends Error {
  constructor(msg) {
    super(msg);
    Error.captureStackTrace(this, AppError); // hide constructor frame
  }
}

7. Handling Uncaught Exceptions

Example

process.on("uncaughtException", (err, origin) => {
  logger.fatal({ err, origin });
  process.exit(1); // exit; let supervisor restart
});
Warning: Don't continue after uncaughtException — process state may be corrupt.

8. Handling Unhandled Rejections

APIUse
process.on("unhandledRejection", h)Last-resort handler
--unhandled-rejections=strictCrash on unhandled (default since v15)

9. Implementing Error Middleware

Example: Express style

app.use((err, req, res, next) => {
  const status = err.status ?? 500;
  res.status(status).json({ error: { code: err.code, message: err.message } });
});

10. Using Domain Module

StatusDetail
DEPRECATEDReplaced by AsyncLocalStorage + structured error handling

11. Graceful Error Recovery

StrategyUse
Circuit breakersStop cascading failures (e.g., opossum)
Retry with backoffTransient errors only
BulkheadsIsolate resources per dependency
TimeoutsBound every external call

12. Logging Errors

PracticeDetail
StructuredJSON, with err code/stack
Include cause chainWalk err.cause
Don't log secretsRedact tokens, PII
Send to APMSentry, Datadog, NewRelic