← Back to JavaScript, page 9

javascript-0172 · Medium mid

What are Error.cause and AggregateError, and how do you use them to keep the full story of a failure?

Passing { cause } as the second argument of an Error constructor links a low-level error to the higher-level one you throw, so wrapping an error does not lose the original stack or message. AggregateError holds many errors in its errors array, and Promise.any rejects with it when every promise fails. Log the whole chain, rethrow with context, and do not swallow the original.

Full answer

When code catches an error and throws a new one with a clearer message, the original error is often lost. Error.cause fixes that: new Error('Could not load profile', { cause: original }). The cause is stored as an own, non-enumerable property named cause, and it can be any value, not only an error. Each layer adds context for the reader of the log, while the root cause keeps its own stack.

Practical points:

  • Wrap at boundaries: a database layer throws a driver error, the service layer wraps it as "could not save order", and the HTTP layer converts it to a response. Logs should walk the chain through cause.
  • Custom errors should pass the options through: class AppError extends Error { constructor(message, options) { super(message, options); this.name = 'AppError'; } }.
  • cause is non-enumerable, so JSON.stringify(error) does not include it, and neither does { ...error }. Write a small serializer that walks the chain. Also protect against cycles.
  • AggregateError(errors, message) represents several failures at once. It has an errors array. Promise.any rejects with an AggregateError when all the input promises reject, and Promise.allSettled is the way to keep every result without a rejection.
  • Do not use cause for control flow. Use it for diagnosis, and match on error types or codes (error.code) for logic.
  • Browsers and Node.js print the cause when the error is logged with console.error, but custom log pipelines need to read the property.
  • The stack is a string created when the error is constructed, so create wrapping errors at the place of the failure, not in a helper that adds noise.

Avoid catching only to log and rethrow without adding information. Either add context with a cause, handle the error, or let it propagate.

javascript
class AppError extends Error {
  constructor(message, options) {
    super(message, options);
    this.name = 'AppError';
  }
}

function readConfig() {
  try {
    return JSON.parse('{ "port": ');
  } catch (error) {
    throw new AppError('Could not read the config', { cause: error });
  }
}

function startServer() {
  try {
    return readConfig();
  } catch (error) {
    throw new AppError('Server failed to start', { cause: error });
  }
}

function describe(error, seen = new Set()) {
  const chain = [];
  let current = error;
  while (current && !seen.has(current)) {
    seen.add(current);
    chain.push(`${current.name}: ${current.message}`);
    current = current.cause;
  }
  return chain;
}

try {
  startServer();
} catch (error) {
  console.log(describe(error).map((line, depth) => '  '.repeat(depth) + line).join('\n'));
  console.log('own keys:', Object.keys(error), 'has cause:', Object.hasOwn(error, 'cause'));
  console.log('json:', JSON.stringify(error));
  console.log('cause descriptor enumerable:', Object.getOwnPropertyDescriptor(error, 'cause').enumerable);
}

const plain = new Error('wrapped a string', { cause: 'just text' });
console.log('cause can be any value:', plain.cause);
console.log('no options, no property:', Object.hasOwn(new Error('x'), 'cause'));

const loop = new Error('a');
loop.cause = loop;
console.log('cycle protected:', describe(loop));

const fail = (name, delay) => new Promise((_, reject) => setTimeout(() => reject(new Error(name)), delay));
Promise.any([fail('first service', 3), fail('second service', 1)]).catch((error) => {
  console.log(error.constructor.name, '|', error.message, '|', error.errors.map((e) => e.message));
});

const manual = new AggregateError([new TypeError('bad type'), new RangeError('bad range')], 'Validation failed');
console.log(manual.name, manual.errors.length, manual.errors.map((e) => e.name));

Run with Node.js v24.22.1 as js-172.js; two runs gave identical output. Output: AppError: Server failed to start AppError: Could not read the config SyntaxError: Unexpected end of JSON input own keys: [ 'name' ] has cause: true json: {"name":"AppError"} cause descriptor enumerable: false cause can be any value: just text no options, no property: false cycle protected: [ 'Error: a' ] AggregateError 2 [ 'TypeError', 'RangeError' ] AggregateError | All promises were rejected | [ 'first service', 'second service' ]

Key points

  • new Error(message, { cause }) keeps the original error attached to the new one.
  • cause is non-enumerable, so serializers must read it explicitly and guard against cycles.
  • AggregateError holds an errors array; Promise.any rejects with it when all inputs fail.
  • Wrap errors at layer boundaries and match on type or code, not on message text.
  • Do not catch just to log and rethrow without context.

Common mistakes

  • Throwing a new error and losing the original one.
  • Expecting JSON.stringify or spread to copy cause, message, or stack.
  • Using Promise.all when every failure should be collected.
  • Matching on error messages instead of types or codes.

Follow-ups

  • How would you send an error with its cause chain to a logging service?
  • How does AggregateError differ from the result of Promise.allSettled?
  • Where should errors be wrapped in a layered application?

Tips

  • Say cause is for diagnosis, codes and types are for logic.
  • Mention that cause does not survive JSON.stringify.
  • Know that Promise.any rejects with AggregateError.