No Login Data Private Local Save

Error.cause Property Demo - Online Chained Errors

6
0
0
0

Error.cause Property Demo

Explore JavaScript Error.cause to chain errors and preserve debugging context. Build a nested error chain, inspect the cause property, and view stack traces.

Build Error Chain
Error Inspection
Create an error chain to see the output...

Frequently Asked Questions

Error.cause is an ES2022 feature that allows you to specify the underlying reason for an error. It accepts any value, typically another Error object, and preserves the original stack trace and context. This enables chained errors – a pattern where a higher‑level error wraps a lower‑level one without losing debugging information.

try {
    throw new Error("Network timeout");
} catch (originalError) {
    throw new Error("File upload failed", { cause: originalError });
}
You can chain more levels by nesting further.

Error.cause is supported in all modern browsers (Chrome ≥93, Firefox ≥91, Safari ≥15, Edge ≥93) and Node.js ≥16.9.0. For older environments consider a polyfill or manual cause tracking.

No, the cause property is read‑only. Instead, create a new error and assign the original error as its cause.

With cause you get automated standardized chaining, whereas manually concatenating messages loses the original error object and stack trace. Debugging tools and logging libraries can automatically traverse the cause property to present a full error chain.

function logErrorChain(err) {
    let current = err;
    let level = 0;
    while (current) {
        console.log(`Level ${level}: ${current.message}`);
        if (current.stack) console.log(current.stack);
        current = current.cause;
        level++;
    }
}

Absolutely. The cause option works with any built‑in or custom error class that extends Error. Just pass { cause: previousError } to the constructor.

Chained errors preserve full context – you can trace back from a user‑facing message to the root technical cause. This dramatically speeds up debugging and improves error reporting in services like Sentry or DataDog.

By default, JSON.stringify on an Error object returns {}. The cause property is enumerable and will appear in JSON.stringify(err) as "cause":{...}, but you may need a custom replacer to capture message and stack properly.

You can create a wrapper that mimics the behavior:
class ChainedError extends Error {
    constructor(message, originalError) {
        super(message);
        this.cause = originalError;
    }
}
Though not a full polyfill, it provides the chaining pattern until native support is available.