JavaScript Reference ยท JSON, Errors and Reflection
Error cause
Reference for the Error cause option: wrap a low-level error in a higher-level one without losing the original, read error.cause and walk a chain of causes.
When a low-level failure happens deep in your code, the code that catches it often wants to throw a better, more specific error: "Could not load settings" instead of "Unexpected token". If you simply throw the new error, the original information is lost. The cause option solves this by attaching the original error to the new one.
Pass { cause } as the second argument of any error constructor. The value is stored on the new error as its cause property, so debuggers and your own handlers can follow the chain back to the root problem.
try { JSON.parse("{"); } catch (error) { throw new Error("Could not read settings", { cause: error }); }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
new Error(message, { cause }) new TypeError(message, { cause }) // ...every native error type accepts the same options
| Name | Description |
|---|---|
options.cause |
Any value, usually the caught error. It becomes error.cause. |
Return value: the new error. The cause property is an own, non-enumerable data property, created only if options has a cause property (even with the value undefined).
Exceptions: none. If options is not an object, it is ignored.
Usage notes
- Add context, keep the original. Wrap an error when your layer can say something more useful, and always pass the original as the cause.
causecan be any value, but errors are by far the most helpful. Avoid strings that merely repeat the message.- Custom subclasses must forward
optionstosuper(message, options), as in the example, or the cause is lost. - Chains can be walked with a loop (
while (e) { ...; e = e.cause }). Guard against cycles if the data is not fully under your control. - Not enumerable, so
JSON.stringify(error)and spread do not include it. Log it deliberately. - Consoles show it. Current browser dev tools and Node.js print the cause chain when you log an error, but the output format is not standardized.
- Do not wrap needlessly. If the original error already says what you would say, rethrow it unchanged.
AggregateErrortakes the same options object as its third argument.
Browser support
The cause option is a fairly recent addition, supported in current browsers and Node.js. Check a compatibility table if you must support older environments.
Related
Error, error types,AggregateError,try...catch- Lessons: Errors, Throwing errors