---
title: "Chain errors with the cause option · Ihab Khattab"
description: "When throwing a new error, pass the original one as cause. Debugging gets easier because the original error and its stack trace are kept."
url: "https://ihabkhattab.com/til/error-cause/"
---

# Chain errors with the cause option

Jul 24, 2024 · [Also on X](https://x.com/HO_BA/status/1816073285290828047)

When throwing a new error, pass the original one as `cause`. Debugging gets easier because the original error and its stack trace are kept.

```js
try {
  connectToDatabase();
} catch (err) {
  throw new Error("Connecting to database failed.", { cause: err });
}
```

This way, the logs show both what failed and why. [MDN: Error.cause](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause)

[← All TILs](https://ihabkhattab.com/til/)
