是否有可能捕获在异步回调中抛出的异常? [英] Is it possible to catch exceptions thrown in a JavaScript async callback?
问题描述
有没有办法在JavaScript回调中捕获异常?是否可能?
Is there a way to catch exceptions in JavaScript callbacks? Is it even possible?
Uncaught Error: Invalid value for property <address>
这里是jsfiddle: http://jsfiddle.net/kjy112/yQhhy/
Here is the jsfiddle: http://jsfiddle.net/kjy112/yQhhy/
try {
// 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) {
if (geoStatus != google.maps.GeocoderStatus.OK) console.log(geoStatus);
}
);
} catch (e) {
if(e instanceof TypeError)
alert('TypeError');
else
alert(e);
}
推荐答案
t catch你的例子中的任何东西是因为一旦 geocode()
回调被调用, try / catch
。因此, geocode()
回调在 try
块的范围之外执行,因此无法捕获。
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.
据我所知,不可能捕获在JavaScript回调中抛出的异常(至少不是以任何直接的方式)。
As far as I know, it is not possible to catch exceptions thrown in JavaScript callbacks (at least, not in any straightforward manner).
这篇关于是否有可能捕获在异步回调中抛出的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!