jQuery Catch 语句不捕获抛出的错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16316815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Catch statement does not catch thrown error
提问by Xenology
For some reason this code gives me an uncaught exception error. It seems the catch block is not catching the error. Are try catch blocks scoped in such a way that I cannot throw an error in a nested function, and then expect it to be caught by a catch statement scoped higher up the chain? Some of the sensitive data with in the application that i'm working in has been removed, but it expected that leadInfo[ 0 / 1] would be a 32 character alpha numeric string that I pull from URL parameters.
出于某种原因,这段代码给了我一个未捕获的异常错误。似乎 catch 块没有捕获错误。try catch 块的范围是否使我不能在嵌套函数中抛出错误,然后期望它被作用域链更高的 catch 语句捕获?我正在使用的应用程序中的一些敏感数据已被删除,但它预计 LeadInfo[ 0 / 1] 将是我从 URL 参数中提取的 32 个字符的字母数字字符串。
The underlying issue here is with my AJAX call returning an error from the API and that error not being handled properly within the application. Hence the need for the throw statement. The AJAX call completes fine, and returns a JSON object that does not contain the email address as a property, so I need to handle that in a way that changes the page to reflect that.
这里的潜在问题是我的 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();
}
});
回答by flavian
The reason why your try catch
block is failing is because an ajax request is asynchronous. The try catch block will execute before the Ajax call and send the request itself, but the error is thrown when the result is returned, AT A LATER POINT IN TIME.
您的try catch
块失败的原因是因为 ajax 请求是异步的。try catch 块将在 Ajax 调用之前执行并发送请求本身,但在返回结果时会抛出错误,稍后时间。
When the try catch
block is executed, there is no error. When the error is thrown, there is no try catch
. If you need try catch
for ajax requests, always put ajax try catch
blocks inside the success
callback, NEVER outside of it.
当try catch
块被执行时,没有错误。抛出错误时,没有try catch
. 如果您需要try catch
ajax 请求,请始终将 ajaxtry catch
块放在success
回调中,永远不要放在回调之外。
Here's how you should do it:
以下是您应该如何做:
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");
};
}
回答by MarioDS
The problem is that ajax is asynchronous by definition. Your exception does not get thrown from within the $.ajax
function, but from the callbackfunction on success (which is triggered at a later time).
问题是 ajax 根据定义是异步的。您的异常不会从$.ajax
函数内部抛出,而是从成功时的回调函数抛出(稍后触发)。
You should give an error: function(data) {}
parameter to it as well, to handle server response errors, and furthermore you should place the try/catch block insidethe callback function.
您还应该给error: function(data) {}
它一个参数,以处理服务器响应错误,此外,您应该将 try/catch 块放在回调函数中。
If you really want to catch it outside the callback, then you should consider calling a function rather than throwing an exception, because I don't see how it can be done.
如果你真的想在回调之外捕获它,那么你应该考虑调用一个函数而不是抛出异常,因为我不知道它是如何完成的。
回答by jap1968
Due to the asynchronous nature of the callback methods in javascript, the context of the function throwing the error is different compared to the original one. You should do this way:
由于 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
}
}
I would suggest you to have a look at this excellent articleabout the (very particular) contexts, closuresand bindingsin Javascript.