Skip to content

Instantly share code, notes, and snippets.

@getify
Last active December 19, 2015 19:58
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getify/6009932 to your computer and use it in GitHub Desktop.
Save getify/6009932 to your computer and use it in GitHub Desktop.
Improve the string serialization output of Error objects using `.stack`, if it's available (recent Chrome and Firefox do!)
// hopefill to wrap the built-in Error.prototype.string() with an improved version
(function(){
var errToString = Error.prototype.toString;
Error.prototype.toString = function() {
var stack;
// some browsers track the much more useful `.stack`, so use it!
if (this.stack) {
// some print the name/message in .stack, some don't. normalize it.
stack = (this.stack + "").replace(new RegExp(this.name + ": " + this.message + "\n"),"");
return this.name + ": " + this.message + "\n" + stack;
}
// otherwise, just use whatever the built-in behavior is.
else {
return errToString.call(this);
}
};
})();
function blah() {
function foo() {
var a = true;
try { a(); }
catch (err) {
console.log(err); // outputs just the err object
console.log(err+""); // forces err#toString to get nicer output
}
}
foo();
}
blah();
// Chrome outputs:
TypeError {}
TypeError: boolean is not a function
at foo (<anonymous>:23:15)
at blah (<anonymous>:29:5)
at <anonymous>:32:1
// Firefox outputs:
[object Error]
TypeError: a is not a function
foo@debugger eval code:22
blah@debugger eval code:28
@debugger eval code:31
@getify
Copy link
Author

getify commented Jul 16, 2013

I've filed enhancement suggestions for both Chrome and Firefox to do this built-in (please go vote on them!):

Chrome: https://code.google.com/p/chromium/issues/detail?id=260740

Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=894446

@getify
Copy link
Author

getify commented Jul 16, 2013

Apparently this will need to be proposed to change the actual ES spec: http://es5.github.io/#x15.11.4.4 So I've asked a few committee members to get a sense of it.

@rwaldron
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment