Last active
December 19, 2015 19:58
-
-
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!)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
}; | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://wiki.ecmascript.org/doku.php?id=strawman:error_stack