occ / TraceKit

Attempts to create stack traces for unhandled JavaScript exceptions in all major browsers.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Utilize `.toString` hack to get `Error` during `window.onerror`

JamesMGreene opened this issue · comments

I came up with a clever technique a few months ago that I wanted to try out... turns out to be a win but only in Firefox (so far as I've seen):
    http://jsfiddle.net/JamesMGreene/MYgpY/

Basically you override the Error.prototype.toString method to store a reference to that Error so that you can access it again during the window.onerror handler even if the 5th error argument does not exist. This works on the notion that the browsers would invoke the toString (or valueOf) method when getting the string to pass as the 1st message argument to window.onerror; however, it turns out that this assumption is only currently valid in Firefox (as far as major browsers go, anyway)... the others seem to utilize some internal conversion approach instead. Either way, it's easy to feature test and can be a big win in Firefox.

P.S. This obviously doesn't work on any custom Error types that override the toString method but I've found it very useful all the same. If they are your own Error types, you can utilize this same technique in the class's own toString method — Firefox will still call it even if it's not at the Error.prototype.toString level.

For example:
    http://jsfiddle.net/JamesMGreene/D6nNy/

@JamesMGreene I'm helping maintain TraceKit upstream.. If you want to recreate this issue in the master (https://github.com/csnover/TraceKit). I'd be open to taking a closer look into this.