有没有办法在 JavaScript 回调中捕获异常?有可能吗?
Uncaught Error: Invalid value for property <address>
这是 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);
}
原文由 anewb 发布,翻译遵循 CC BY-SA 4.0 许可协议
它不会在您的示例中捕获任何内容的原因是因为一旦调用了
geocode()
回调,try/catch
块就结束了。因此geocode()
回调在try
块的范围之外执行,因此无法被它捕获。据我所知,不可能捕获 JavaScript 回调中抛出的异常(至少,不能以任何直接的方式)。