← All posts

TIL: Error.cause — Chain Errors Without Losing Context

ES2022 lets errors carry a cause so the original exception is never silently swallowed.

Michael Cooper2 min readYellow belt

The problem

When you catch a low-level error and throw a higher-level one, the original message disappears:

js
async function fetchUser(id) {
  try {
    return await db.query('SELECT * FROM users WHERE id = $1', [id]);
  } catch (err) {
    throw new Error('Failed to load user'); // original error is gone
  }
}

The stack trace points to your new Error, but the actual database error—table does not exist, connection reset, constraint violation—is silently swallowed. The cause option fixes that.

The fix

ES2022 added a second argument to the Error constructor:

js
throw new Error('Failed to load user', { cause: err });

The original error is stored on error.cause and Node.js prints both in its default output:

Error: Failed to load user
    at fetchUser (app.js:6:11)
Caused by: Error: relation "users" does not exist
    at ...

A realistic TypeScript pattern

ts
async function fetchUser(id: string): Promise<User> {
  try {
    const result = await db.query<User>(
      'SELECT * FROM users WHERE id = $1',
      [id],
    );
    return result.rows[0];
  } catch (err) {
    throw new Error(`fetchUser(${id}) failed`, { cause: err });
  }
}

async function handleRequest(id: string) {
  try {
    const user = await fetchUser(id);
    return Response.json(user);
  } catch (err) {
    if (err instanceof Error) {
      console.error('Request error:', err.message);
      console.error('Caused by:', err.cause);
    }
    return Response.json({ error: 'Internal server error' }, { status: 500 });
  }
}

Walking the chain

TypeScript types cause as unknown, which is correct since any value is valid. Walk the chain safely with a helper:

ts
function getRootMessage(err: unknown): string {
  if (err instanceof Error) {
    return err.cause ? getRootMessage(err.cause) : err.message;
  }
  return String(err);
}

// getRootMessage(fetchError) → "relation \"users\" does not exist"

Support

| Environment | Minimum version | |---|---| | Node.js | 16.9 | | Chrome | 93 | | Firefox | 91 | | Safari | 15 | | TypeScript | 4.6 |

No polyfill needed for any actively maintained Node.js or browser release.