有没有办法在 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);
}
最佳答案
它不会在您的示例中捕获任何内容的原因是因为一旦调用了 geocode()
回调,try/catch
block 就结束了。因此,geocode()
回调在 try
block 的范围之外执行,因此无法被它捕获。
据我所知,不可能捕捉到 JavaScript 回调中抛出的异常(至少,不是以任何直接的方式)。
关于javascript - 是否可以捕获 JavaScript 异步回调中抛出的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3677783/