Catch语句不会捕获抛出的错误

由于某种原因,此代码给了我一个未捕获的exception错误。 似乎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(); } }); 

你的try catch块失败的原因是因为ajax请求是异步的。 try catch块将在Ajax调用之前执行并自行发送请求,但是返回结果时会抛出错误,AT A LATER POINT IN TIME。

执行try catch块时,没有错误。 抛出错误时,没有try catch 。 如果你需要try catch for ajax请求,总是把ajax try catch块放在success回调中,永远不要在它之外。

这是你应该怎么做的:

 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"); }; } 

问题是ajax根据定义是异步的。 您的exception不会从$.ajax函数中抛出,而是从成功的回调函数(稍后触发)中抛出。

你应该给它一个error: function(data) {}参数,处理服务器响应错误,此外你应该把try / catch块放在回调函数中。

如果你真的想在回调之外捕获它,那么你应该考虑调用一个函数而不是抛出exception,因为我看不出它是如何完成的。

由于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中(非常特殊的) 上下文闭包绑定的优秀文章 。