How can I preserve the original error when adding context to an async failure?
Quick answer
When you catch a failure, wrap it in a new Error that describes the operation and pass the caught value as its cause. For example, use throw new Error("Loading records failed", { cause: err }). The higher-level caller can read the context from the wrapper and inspect cause for the underlying failure; distinguish errors by their causes or types, not by parsing message text. [S1]
The question, the details, the next step.
A practical checklist
Name the operation or stage that failed in the wrapper message.
Pass the caught value as
{ cause: err }when constructing the newError.Let the contextual error reach the layer that needs to inspect or handle it.
Use causes or suitable error types for distinctions; do not parse message text.
Check runtime and build-target support for the
causeoption.
A few more useful answers
Should I replace the caught error’s message with a more descriptive one?
Add a contextual wrapper and retain the caught value as its cause. That keeps the operation context and the underlying failure available separately. [S1]
Can I rely on the exact wording of an error message to identify its cause?
Avoid that approach. The reference recommends using cause to distinguish errors rather than parsing messages. [S1]
Does this pattern work in every JavaScript runtime or build target?
The cited reference notes that availability and transpilation details may vary. Check the environment your code targets; the source does not establish universal compatibility. [S1]
Sources
References used for this guide.
- [S1] JavaScript Error object: preserving an underlying cause learn.microsoft.com · Checked
