出于某种原因,这段代码给了我一个无法捕捉的异常错误。catch块似乎没有捕捉到错误。try catch块的作用范围是否如此,以至于我不能在嵌套函数中抛出一个错误,然后期望它被一个作用范围更高的catch语句捕获?我正在使用的应用程序中的一些敏感数据已经被删除,但它预期leadInfo[ 0 / 1]将是一个32个字符的字母数字字符串,我从URL参数中提取。
这里的根本问题是我的AJAX调用从API返回一个错误,而这个错误在应用程序中没有得到正确处理。因此需要throw语句。AJAX调用很好地完成了,并返回一个不包含电子邮件地址属性的JSON对象,所以我需要通过更改页面来反映这一点。
jQuery(document).ready(function(){
try {
url = "http://api.com/api/v1/lead/" + leadInfo[1]
jQuery.ajax({
type: 'GET',
contentType: 'application/json',
url: url,
dataType : 'jsonp',
success: function (result) {
result = jQuery.parseJSON(result);
if(!result.data.email){
throw ('New exception');
}
console.log(result);
jQuery('.email').html(result.data.email);
}
});
jQuery('.surveryButton').click(function(){
window.location.replace("http://" + pgInventory.host + pgInventory.path + leadInfo[0] + "&curLeadId=" + leadInfo[1] + "&curViewedPages=0");
});
}
catch(err) {
jQuery('.email').html('your e-mail address');
jQuery('#arrowContent').remove();
}
});
您的< code>try catch块失败的原因是因为ajax请求是异步的。try catch块将在Ajax调用之前执行,并发送请求本身,但是在稍后返回结果时会抛出错误。
执行<code>try-catch<code>块时,没有错误。当抛出错误时,没有<code>try-catch</code>。如果您需要<code>try-catch
你应该这样做:
success: function (result) {
try {
result = jQuery.parseJSON(result);
if (!result.data.email) {
throw ('New exception');
}
console.log(result);
jQuery('.email').html(result.data.email);
} catch (exception) {
console.error("bla");
};
}
由于 javascript 中回调方法的异步性质,引发错误的函数的上下文与原始函数的上下文不同。您应该这样做:
success: function (result) {
try {
result = jQuery.parseJSON(result);
if(!result.data.email){
throw ('New exception');
}
console.log(result);
jQuery('.email').html(result.data.email);
}
catch(err) {
// Dealing with the error
}
}
我建议您看看这篇关于Javascript中(非常特殊的)上下文、闭包和绑定的优秀文章。
问题在于,根据定义,ajax 是异步的。您的异常不会从 $.ajax
函数内部引发,而是从成功时的回调函数(稍后触发)引发。
您还应该给它一个error: function(data){}
参数来处理服务器响应错误,此外,您应该将try/catch块放在回调函数中。
如果你真的想在回调之外抓住它,那么你应该考虑调用一个函数而不是抛出一个异常,因为我看不出它是如何做到的。