← Back to Node.js, page 2

nodejs-0030 · Hard senior

How do you design custom errors in Node.js, and what is the difference between operational errors and programmer errors?

Create error classes that extend Error, with a stable code, an HTTP status when needed, and the original error in the cause option. Operational errors are expected runtime problems (bad input, a down service) that code can handle. Programmer errors are bugs (TypeError, wrong arguments) that should crash and be fixed.

Full answer

Why custom errors: callers should branch on a stable property, not on message text. A good design has:

  • A base class AppError extends Error with name, code (a string like 'ORDER_NOT_FOUND'), and optionally statusCode and details.
  • Subclasses for common cases: ValidationError (400), NotFoundError (404), DependencyError (502).
  • The original error kept as the cause: new AppError('Could not load marks', { cause: err }). Node prints the cause chain, and err.cause lets you log the root problem without losing context.
  • Error.captureStackTrace(this, this.constructor) is optional in modern V8, since the stack is captured in the Error constructor already.

Operational vs programmer errors:

  • Operational: the program is right but the world is not. Examples: user sent invalid JSON, a database timed out, a file is missing. Handle them: retry, show a clear message, return 4xx or 5xx.
  • Programmer: a bug. Examples: reading a property of undefined, passing a number where a string is required. Do not catch them to hide them. Log, crash, restart, fix.

For many errors at once (validation of a form with five invalid fields, or Promise.any failing), use AggregateError, which holds an errors array.

Never send stack traces or internal messages to clients. Map the error to a safe message and code in one place, such as an HTTP error middleware, and log the full detail on the server.

javascript
class AppError extends Error {
  constructor(message, { code = 'APP_ERROR', statusCode = 500, cause } = {}) {
    super(message, { cause });
    this.name = this.constructor.name;
    this.code = code;
    this.statusCode = statusCode;
  }
}
class NotFoundError extends AppError {
  constructor(what, options) {
    super(`${what} not found`, { code: 'NOT_FOUND', statusCode: 404, ...options });
  }
}

function findStudent(id) {
  try {
    if (id !== 1) throw new RangeError('row missing in the in-memory table'); // low-level detail
    return { id, name: 'Asha' };
  } catch (err) {
    throw new NotFoundError(`Student ${id}`, { cause: err });
  }
}

// Convert errors to safe responses in one place.
function toResponse(err) {
  if (err instanceof AppError) return { status: err.statusCode, body: { code: err.code, message: err.message } };
  return { status: 500, body: { code: 'INTERNAL', message: 'Something went wrong' } }; // programmer error: no details
}

try {
  findStudent(7);
} catch (err) {
  console.log('name:', err.name, '| code:', err.code, '| instanceof AppError:', err instanceof AppError);
  console.log('cause:', err.cause.name + ': ' + err.cause.message);
  console.log('response:', JSON.stringify(toResponse(err)));
  console.log('unknown error response:', JSON.stringify(toResponse(new TypeError('x is undefined'))));
}

const many = new AggregateError([new Error('name is empty'), new Error('age must be a number')], 'Validation failed');
console.log(many.message, '->', many.errors.map((e) => e.message));

The unknown TypeError shows the safe fallback: the client gets no internal detail. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): name: NotFoundError | code: NOT_FOUND | instanceof AppError: true cause: RangeError: row missing in the in-memory table response: {"status":404,"body":{"code":"NOT_FOUND","message":"Student 7 not found"}} unknown error response: {"status":500,"body":{"code":"INTERNAL","message":"Something went wrong"}} Validation failed -> [ 'name is empty', 'age must be a number' ]

Key points

  • Extend Error, add a stable code, and keep the original error in cause.
  • Branch on code or instanceof, never on message text.
  • Operational errors are handled. Programmer errors crash and get fixed.
  • AggregateError groups several errors.
  • Map errors to safe client responses in one place.

Common mistakes

  • Matching errors by message text.
  • Returning err.message or err.stack of an unknown error to the client.
  • Catching a TypeError and carrying on, which hides a bug.
  • Losing the original error when wrapping, so the root cause is gone from the logs.

Follow-ups

  • How would you log a cause chain in JSON?
  • Should a library throw strings? Why not?
  • How do you test that a function throws a specific error class?

Tips

  • Define both error kinds in one sentence each, with an example.
  • Show the cause option, since many candidates still use it rarely.
  • Say where the mapping to HTTP responses lives.