Q: window.onerror doesn't work in mobile -- How should I deal with unhandled exceptions? I'm working on a complex web application written in Sencha Touch and PhoneGap.  The way Sencha Touch applications are written makes it hard to surround every potential failure point with a try/catch, especially with asynchronous AJAX request handlers.
It's also critically important to detect when an unhandled exception occurs because it looks and feels like a native app with PhoneGap (i.e. we can't expect them to refresh the page and try again like in a web app you view in a regular browser).
Can you suggest a recommendation for how to deal with this scenario?

A: It's a great question. Of course the window error event should never replace strategically placed try/catch blocks or good use of error responses from HTTP requests, but until the mobile browsers catch up with the desktop versions, reporting back truly unexpected errors is near impossible.
I don't have time to test this out; so all I can suggest is a thought experiment at the moment for what is in all honesty probably a bad idea...
You could potentially write replacement functions for addEventListener (and maybe dispatchMethod) that could wrap the native functions / handler arguments with try/catch and call a custom global error logger. Since there is no easy way to 'hook' these functions all at once, it would no doubt mean iterating over many of the native objects' prototypes on window to perform the 'wrapping'. This could cover a large majority of exceptions that would currently go silent.

A: I don't think it needs to be expensive to safely wrap all the relevant handlers. Most likely you (or Sencha Touch) are already relying on something like jQuery to establish your event handlers in the most cross-platform way. So everything is getting set up by a small number of functions, so there are only a few places that need patching.
In other words, don't try patching at the lowest level (every node's addEventListener). Patch (or write) a few library functions and then always use them to establish your event listeners.
If you load your error trapping code first (before anyone else has a chance to grab references to the relevant functions), and patch jQuery.bind and window.setTimeout you'll get pretty good coverage. For Ajax, there are already good hooks (like jQuery.ajaxPrefilter) where you can insert your exception traps by wrapping the response handlers in closures.
