Error Polyfill for V8 Stack Trace API

0.1.3 · abandoned · verified Sun Apr 19

The `error-polyfill` package provides a polyfill for the V8 Stack Trace API, enabling functionalities like `Error.captureStackTrace` and `Error.prepareStackTrace` in non-V8 JavaScript environments. It aims to standardize how stack traces are generated and accessed across various engines and browsers, including older versions of Node.js, Chrome, Firefox, Internet Explorer, and PhantomJS. The current stable version is 0.1.3, suggesting an early stage of development and a lack of recent updates. A key differentiator is the `Error.getStackTrace` utility, which is recommended for reliably accessing formatted stack traces, as direct `throwable.stack` access might be inconsistent or unformatted in polyfilled environments. The library explicitly requires ES5 support to function.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load the `error-polyfill`, define a custom error using the polyfilled `Error.captureStackTrace` for structured stack tracing, and then retrieve the formatted stack trace using the recommended `Error.getStackTrace` in both error handling and for general stack capture scenarios.

require("error-polyfill");

// Define a custom error to demonstrate captureStackTrace
var CustomError = function (message) {
    this.name = "CustomError";
    this.message = message;
    // Capture the current stack trace, excluding the CustomError constructor call
    Error.captureStackTrace(this, this.constructor);
};
// Inherit from Error.prototype to ensure proper error instance behavior
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError; // Maintain correct constructor reference

function doSomethingWithError() {
    function triggerError() {
        throw new CustomError("An intentional error occurred!");
    }
    triggerError();
}

try {
    doSomethingWithError();
} catch (error) {
    console.log("Caught an error:");
    if (error instanceof CustomError) {
        console.log(`  Type: ${error.name}`);
        console.log(`  Message: ${error.message}`);
    }
    // Always use Error.getStackTrace for consistent results with this polyfill
    console.log("  Stack Trace:\n" + Error.getStackTrace(error));
}

// Example of capturing a stack without throwing an error
const myObject = {};
Error.captureStackTrace(myObject);
console.log('\nCaptured stack for a plain object:\n' + Error.getStackTrace(myObject));

view raw JSON →