error-polyfill v0.1.3
Javascript Error Polyfill
Implementing the V8 Stack Trace API in non-V8 environments as much as possible
Installation
npm install error-polyfillbower install error-polyfillEnvironment compatibility
Tested on the following environments:
Windows 7
- Node.js 9.6
- Chrome 64.0
- Firefox 58.0
- Internet Explorer 10.0, 11.0
- PhantomJS 2.1
- Opera 51.0
Travis
- Node.js 8, 9
- Chrome
- Firefox
PhantomJS
The polyfill might work on other environments too due to its adaptive design. I use Karma with Browserify to test the framework in browsers.
Requirements
ES5 support is required, without that the lib throws an Error and stops working.
The ES5 features are tested by the capability lib run time. Classes are created by the o3 lib. Utility functions are implemented in the u3 lib.
API documentation
Usage
In this documentation I used the framework as follows:
require("error-polyfill");
// <- your code hereIt is recommended to require the polyfill in your main script.
Getting a past stack trace with Error.getStackTrace
This static method is not part of the V8 Stack Trace API, but it is recommended to use Error.getStackTrace(throwable) instead of throwable.stack to get the stack trace of Error instances!
Explanation:
By non-V8 environments we cannot replace the default stack generation algorithm, so we need a workaround to generate the stack when somebody tries to access it. So the original stack string will be parsed and the result will be properly formatted by accessing the stack using the Error.getStackTrace method.
Arguments and return values:
- The
throwableargument should be anError(descendant) instance, but it can be anObjectinstance as well. - The return value is the generated
stackof thethrowableargument.
Example:
try {
theNotDefinedFunction();
}
catch (error) {
console.log(Error.getStackTrace(error));
// ReferenceError: theNotDefinedFunction is not defined
// at ...
// ...
}Capturing the present stack trace with Error.captureStackTrace
The Error.captureStackTrace(throwable [, terminator]) sets the present stack above the terminator on the throwable.
Arguments and return values:
- The
throwableargument should be an instance of anErrordescendant, but it can be anObjectinstance as well. It is recommended to useErrordescendant instances instead of inline objects, because we can recognize them by type e.g.error instanceof UserError. - The optional
terminatorargument should be aFunction. Only the calls before this function will be reported in the stack, so without aterminatorargument, the last call in the stack will be the call of theError.captureStackTrace. - There is no return value, the
stackwill be set on thethrowableso you will be able to access it usingError.getStackTrace. The format of the stack depends on theError.prepareStackTraceimplementation.
Example:
var UserError = function (message){
this.name = "UserError";
this.message = message;
Error.captureStackTrace(this, this.constructor);
};
UserError.prototype = Object.create(Error.prototype);
function codeSmells(){
throw new UserError("What's going on?!");
}
codeSmells();
// UserError: What's going on?!
// at codeSmells (myModule.js:23:1)
// ...Limitations:
By the current implementation the terminator can be only the Error.captureStackTrace caller function. This will change soon, but in certain conditions, e.g. by using strict mode ("use strict";) it is not possible to access the information necessary to implement this feature. You will get an empty frames array and a warning in the Error.prepareStackTrace when the stack parser meets with such conditions.
Formatting the stack trace with Error.prepareStackTrace
The Error.prepareStackTrace(throwable, frames [, warnings]) formats the stack frames and returns the stack value for Error.captureStackTrace or Error.getStackTrace. The native implementation returns a stack string, but you can override that by setting a new function value.
Arguments and return values:
- The
throwableargument is anErrororObjectinstance coming from theError.captureStackTraceor from the creation of a newErrorinstance. Be aware that in some environments you need to throw that instance to get a parsable stack. Without that you will get only awarningby trying to access the stack withError.getStackTrace. - The
framesargument is an array ofFrameinstances. Eachframerepresents a function call in the stack. You can use these frames to build a stack string. To access information about individual frames you can use the following methods. frame.toString()- Returns the string representation of the frame, e.g.codeSmells (myModule.js:23:1).frame.getThis()- Cannot be supported. Returns the context of the call, only V8 environments support this natively.frame.getTypeName()- Not implemented yet. Returns the type name of the context, by the global namespace it isWindowin Chrome.frame.getFunction()- Returns the called function orundefinedby strict mode.frame.getFunctionName()- Not implemented yet. Returns the name of the called function.frame.getMethodName()- Not implemented yet. Returns the method name of the called function is a method of an object.frame.getFileName()- Not implemented yet. Returns the file name where the function was called.frame.getLineNumber()- Not implemented yet. Returns at which line the function was called in the file.frame.getColumnNumber()- Not implemented yet. Returns at which column the function was called in the file. This information is not always available.frame.getEvalOrigin()- Not implemented yet. Returns the original of anevalcall.frame.isTopLevel()- Not implemented yet. Returns whether the function was called from the top level.frame.isEval()- Not implemented yet. Returns whether the called function waseval.frame.isNative()- Not implemented yet. Returns whether the called function was native.frame.isConstructor()- Not implemented yet. Returns whether the called function was a constructor.- The optional
warningsargument contains warning messages coming from the stack parser. It is not part of the V8 Stack Trace API. - The return value will be the stack you can access with
Error.getStackTrace(throwable). If it is an object, it is recommended to add atoStringmethod, so you will be able to read it in the console.
Example:
Error.prepareStackTrace = function (throwable, frames, warnings) {
var string = "";
string += throwable.name || "Error";
string += ": " + (throwable.message || "");
if (warnings instanceof Array)
for (var warningIndex in warnings) {
var warning = warnings[warningIndex];
string += "\n # " + warning;
}
for (var frameIndex in frames) {
var frame = frames[frameIndex];
string += "\n at " + frame.toString();
}
return string;
};Stack trace size limits with Error.stackTraceLimit
Not implemented yet.
You can set size limits on the stack trace, so you won't have any problems because of too long stack traces.
Example:
Error.stackTraceLimit = 10;Handling uncaught errors and rejections
Not implemented yet.
Differences between environments and modes
Since there is no Stack Trace API standard, every browsers solves this problem differently. I try to document what I've found about these differences as detailed as possible, so it will be easier to follow the code.
Overriding the error.stack property with custom Stack instances
- by Node.js and Chrome the
Error.prepareStackTrace()can override everyerror.stackautomatically right by creation - by Firefox, Internet Explorer and Opera you cannot automatically override every
error.stackby native errors by PhantomJS you cannot override the
error.stackproperty of native errors, it is not configurable
Capturing the current stack trace
- by Node.js, Chrome, Firefox and Opera the stack property is added by instantiating a native error
- by Node.js and Chrome the stack creation is lazy loaded and cached, so the
Error.prepareStackTrace()is called only by the first access - by Node.js and Chrome the current stack can be added to any object with
Error.captureStackTrace() - by Internet Explorer the stack is created by throwing a native error
by PhantomJS the stack is created by throwing any object, but not a primitive
Accessing the stack
- by Node.js, Chrome, Firefox, Internet Explorer, Opera and PhantomJS you can use the
error.stackproperty by old Opera you have to use the
error.stacktraceproperty to get the stack
Prefixes and postfixes on the stack string
- by Node.js, Chrome, Internet Explorer and Opera you have the
error.nameand theerror.messagein a{name}: {message}format at the beginning of the stack string - by Firefox and PhantomJS the stack string does not contain the
error.nameand theerror.message by Firefox you have an empty line at the end of the stack string
Accessing the stack frames array
- by Node.js and Chrome you can access the frame objects directly by overriding the
Error.prepareStackTrace() by Firefox, Internet Explorer, PhantomJS, and Opera you need to parse the stack string in order to get the frames
The structure of the frame string
- by Node.js and Chrome
- the frame string of calling a function from a module:
thirdFn (http://localhost/myModule.js:45:29) - the frame strings contain an
atprefix, which is not present by theframe.toString()output, so it is added by thestack.toString() - by Firefox
- the frame string of calling a function from a module:
thirdFn@http://localhost/myModule.js:45:29 - by Internet Explorer
- the frame string of calling a function from a module:
at thirdFn (http://localhost/myModule.js:45:29) - by PhantomJS
- the frame string of calling a function from a module:
thirdFn@http://localhost/myModule.js:45:29 - by Opera
the frame string of calling a function from a module:
at thirdFn (http://localhost/myModule.js:45)
Accessing information by individual frames
- by Node.js and Chrome the
frame.getThis()and theframe.getFunction()returnsundefinedby frames originate from strict mode code - by Firefox, Internet Explorer, PhantomJS, and Opera the context of the function calls is not accessible, so the
frame.getThis()cannot be implemented - by Firefox, Internet Explorer, PhantomJS, and Opera functions are not accessible with
arguments.callee.callerby frames originate from strict mode, so by these framesframe.getFunction()can return onlyundefined(this is consistent with V8 behavior)
License
MIT - 2016 Jánszky László Lajos
