Is it possible to catch exceptions thrown in a JavaScript async callback?

Is there a way to catch exceptions in JavaScript callbacks? Is it even possible?

Uncaught Error: Invalid value for property <address>

Here is the jsfiddle: http://jsfiddle.net/kjy112/yQhhy/

try {
    // this will cause an exception in google.maps.Geocoder().geocode() 
    // since it expects a string.
    var zipcode = 30045; 
    var map = new google.maps.Map(document.getElementById('map_canvas'), {
        zoom: 5,
        center: new google.maps.LatLng(35.137879, -82.836914),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    // exception in callback:
    var geo = new google.maps.Geocoder().geocode({ 'address': zipcode }, 
       function(geoResult, geoStatus) {
          if (geoStatus != google.maps.GeocoderStatus.OK) console.log(geoStatus);
       }
    );
} catch (e) {
    if(e instanceof TypeError)
       alert('TypeError');
    else
       alert(e);
}​

Solution 1:

The reason it won't catch anything in your example is because once the geocode() callback is called, the try/catch block is over. Therefore the geocode() callback is executed outside the scope of the try block and thus not catchable by it.

As far as I know, it is not possible to catch exceptions thrown in JavaScript callbacks (at least, not in any straightforward manner).

Solution 2:

Yes, you can override the default behaviour of window.onerror:

window.onerror = function(message, file, lineNumber) {
  // all errors will be caught here
  // you can use `message` to make sure it's the error you're looking for
  // returning true overrides the default window behaviour
  return true; 
};