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

前端 未结 7 1221
春和景丽
春和景丽 2020-11-27 04:15

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

Uncaught Error: Invalid value for property 

7条回答
  •  爱一瞬间的悲伤
    2020-11-27 04:56

    You can indeed catch exceptions that fire within a JavaScript callback function.

    The key is to set up the try/catch block within the callback code, as any try/catch blocks outside the callback code will have already exited by the time the callback code is executed. So while your try/catch block above won't be able to catch any exceptions that get thrown when the callback function is called, you can still do something like this:

    // this will cause an exception ing 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) {
          try {
              if (geoStatus != google.maps.GeocoderStatus.OK) console.log(geoStatus);
          } catch(e){
              alert("Callback Exception caught!");
          }
       }
    );
    

    and you'll be able to capture the exception when it is thrown. I wasn't 100% sure whether that would be the case or not, so I wrote some test code to verify. The exception is captured as expected on Chrome 19.0.1055.1 dev.

提交回复
热议问题