Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

stacktrace-js

stacktracejs8.9mMIT2.0.2TypeScript support: included

Framework-agnostic, micro-library for getting stack traces in all environments

stacktrace, error, debugger, client, browser

readme

stacktrace.js

Generate, parse and enhance JavaScript stack traces in all browsers

Build Status Coverage Status GitHub license CDNJS size with dependencies gzip size module format

Debug and profile your JavaScript with a stack trace of function calls leading to an error (or any condition you specify).

stacktrace.js uses browsers' Error.stack mechanism to generate stack traces, parses them, enhances them with source maps and uses Promises to return an Array of StackFrames.

Upgrading? Check the 0.x -> 1.x Migration Guide

Usage

Get a stack trace from current location

var callback = function(stackframes) {
    var stringifiedStack = stackframes.map(function(sf) {
        return sf.toString();
    }).join('\n');
    console.log(stringifiedStack);
};

var errback = function(err) { console.log(err.message); };

StackTrace.get().then(callback).catch(errback);
//===> Promise(Array[StackFrame], Error)
//===> callback([
//    StackFrame({functionName: 'func1', args: [], fileName: 'file.js', lineNumber: 203, columnNumber: 9}), 
//    StackFrame({functionName: 'func2', args: [], fileName: 'http://localhost:3000/file.min.js', lineNumber: 1, columnNumber: 3284})
//])

You can also get a stack trace synchronously

HEADS UP: This method does not resolve source maps or guess anonymous function names.

StackTrace.getSync();
//==> [
//      StackFrame({functionName: 'func1', args: [], fileName: 'file.js', lineNumber: 203, columnNumber: 9}), 
//      StackFrame({functionName: 'func2', args: [], fileName: 'http://localhost:3000/file.min.js', lineNumber: 1, columnNumber: 3284})
//]

window.onerror integration

Automatically handle errors

window.onerror = function(msg, file, line, col, error) {
    // callback is called with an Array[StackFrame]
    StackTrace.fromError(error).then(callback).catch(errback);
};

Get stack trace from an Error

var error = new Error('BOOM!');

StackTrace.fromError(error).then(callback).catch(errback);
//===> Promise(Array[StackFrame], Error)

Generate a stacktrace from walking arguments.callee

This might capture arguments information, but isn't supported in ES5 strict-mode

StackTrace.generateArtificially().then(callback).catch(errback);
//===> Promise(Array[StackFrame], Error)

Trace every time a given function is invoked

// callback is called with an Array[StackFrame] every time wrapped function is called
var myFunc = function(arg) { return 'Hello ' + arg; };
var myWrappedFunc = StackTrace.instrument(myFunc, callback, errback);
//===> Instrumented Function
myWrappedFunc('world');
//===> 'Hello world'

// Use this if you overwrote you original function
myFunc = StackTrace.deinstrument(myFunc);
//===> De-instrumented Function

Get stacktrace.js

npm install stacktrace-js
bower install stacktrace-js
component install stacktracejs/stacktrace.js
http://cdnjs.com/libraries/stacktrace.js

API

StackTrace.get(/*optional*/ options) => Promise(Array[StackFrame])

Generate a backtrace from invocation point, then parse and enhance it.

(Optional) options: Object

  • filter: Function(StackFrame => Boolean) - Only include stack entries matching for which filter returns true
  • sourceCache: Object (String URL => String Source) - Pre-populate source cache to avoid network requests
  • offline: Boolean (default: false) - Set to true to prevent all network requests

StackTrace.getSync(/*optional*/ options) => Array[StackFrame]

Generate a backtrace from invocation point, then parse it. This method does not use source maps or guess anonymous functions.

(Optional) options: Object

  • filter: Function(StackFrame => Boolean) - Only include stack entries matching for which filter returns true

StackTrace.fromError(error, /*optional*/ options) => Promise(Array[StackFrame])

Given an Error object, use error-stack-parser to parse it and enhance location information with stacktrace-gps.

error: Error

(Optional) options: Object

  • filter: Function(StackFrame => Boolean) - Only include stack entries matching for which filter returns true
  • sourceCache: Object (String URL => String Source) - Pre-populate source cache to avoid network requests
  • offline: Boolean (default: false) - Set to true to prevent all network requests

StackTrace.generateArtificially(/*optional*/ options) => Promise(Array[StackFrame])

Use stack-generator to generate a backtrace by walking the arguments.callee.caller chain.

(Optional) options: Object

  • filter: Function(StackFrame => Boolean) - Only include stack entries matching for which filter returns true
  • sourceCache: Object (String URL => String Source) - Pre-populate source cache to avoid network requests
  • offline: Boolean (default: false) - Set to true to prevent all network requests

StackTrace.instrument(fn, callback, /*optional*/ errback) => Function

  • Given a function, wrap it such that invocations trigger a callback that is called with a stack trace.

  • fn: Function - to wrap, call callback on invocation and call-through

  • callback: Function - to call with stack trace (generated by StackTrace.get()) when fn is called
  • (Optional) errback: Function - to call with Error object if there was a problem getting a stack trace. Fails silently (though fn is still called) if a stack trace couldn't be generated.

StackTrace.deinstrument(fn) => Function

Given a function that has been instrumented, revert the function to it's original (non-instrumented) state.

  • fn: Function - Instrumented Function

StackTrace.report(stackframes, url, message, requestOptions) => Promise(String)

Given an an error message and Array of StackFrames, serialize and POST to given URL. Promise is resolved with response text from POST request.

Example JSON POST data:

{
  message: 'BOOM',
  stack: [
    {functionName: 'fn', fileName: 'file.js', lineNumber: 32, columnNumber: 1},
    {functionName: 'fn2', fileName: 'file.js', lineNumber: 543, columnNumber: 32},
    {functionName: 'fn3', fileName: 'file.js', lineNumber: 8, columnNumber: 1}
  ]
}
  • stackframes: Array(StackFrame) - Previously wrapped Function
  • url: String - URL to POST stack JSON to
  • message: String - The error message
  • requestOptions: Object - HTTP request options object. Only headers: {key: val} is supported.

Browser Support

Sauce Test Status

HEADS UP: You won't get the benefit of source maps in IE9- or other very old browsers.

Using node.js/io.js only?

I recommend the stack-trace node package specifically built for node. It has a very similar API and also supports source maps.

Contributing

This project adheres to the Open Code of Conduct. By participating, you are expected to honor this code.

Want to be listed as a Contributor? Start with the Contributing Guide!

This project is made possible due to the efforts of these fine people:

changelog

v2.0.0

ES6 Support

ES6 code is now parsed and enhanced!

Extensible StackFrames

StackFrames returned are now able to report on whether a function call was a Constructor, native code, or eval code.

MIT License

The community has voted to change the license of the project to the MIT License

v1.3.0

  • Stacktrace.getSync() gets a stack trace, synchronously. It does not attempt to map sources or guess function names, because those typically require network requests.

v1.2.0

  • StackTrace.report now accepts an error message argument, and will add a message: "given thing" to the JSON payload if it is provided.
  • Various bug fixes from v1.1.0

v1.1.0

Better parsing

Updated error-stack-parser to v1.3 which parses eval stack entries in a better way and fixes a bunch of bugs.

Better resource handling

Updated stacktrace-gps. Now reuses the same instance to avoid duplicate requests for the same resource by default.

Better dev experience

JSCS and automated PR testing have been implemented to ensure consistent styles and quick feedback.

Possibly breaking changes: ErrorStackParser now provides it's own polyfill for Array.map and Array.filter. eval information is will display differently in stack traces.

v1.0.0

stacktrace.js is reborn

stacktrace.js is now modularized into 5 projects:

... and putting it all together: stacktrace.js for instrumenting your code and generating stack traces!

Key Features

  • Fully asynchronous API, using Promises. Use your own polyfill or use our distribution with polyfills included. See the Migration Guide
  • Source Maps support
  • Forward-compatible: stacktrace.js no longer assumes a given browser formats Error stacks in a given way. This prevents new browser versions from breaking error parsing
  • Stack entries are now fully parsed and returned as StackFrame objects. Prefer the old format? - just call .toString()!
  • Use only what you need. All 5 projects work independently as well as together!
  • iOS 8+ Safari support

Available everywhere

npm install stacktrace-js
bower install stacktrace-js
component install stacktracejs/stacktrace.js
https://cdnjs.cloudflare.com/ajax/libs/stacktrace.js/1.0.0/stacktrace.min.js

Better for contributors

  • gulp build
  • TravisCI + Sauce for testing a bunch of browsers
  • EditorConfig for style adherence

v0.6.2

  • Ignore test/ dir in bower
  • Migrate references eriwen/javascript-stacktrace -> stacktracejs/stacktrace.js

v0.6.1

  • Fix printStackTrace throws exception with "use strict" code and PhantomJS

v0.6.0

  • Added AMD support using a UMD pattern (thanks @jeffrose)

v0.5.3

  • Fix Chrome 27 detection; Chrome no longer has Error#arguments

v0.5.1

  • Fix Bower integration; Added proper bower.json file

v0.5.0

  • Lots and lots of stuff