【发布时间】:2013-07-17 23:54:57
【问题描述】:
假设我在函数中有这个 jQuery AJAX 调用:
function callPageMethod(methodName, parameters) {
var pagePath = window.location.href;
$.ajax({
type: "POST",
url: pagePath + "/" + methodName,
contentType: "application/json; charset=utf-8",
data: parameters,
dataType: "json",
success: function (response) {
alert("ajax successful!");
},
error: function (response) {
// this line is not working!
throw response.responseText;
}
});
} // end of function
...我在 Visual Studio 2010 中收到此错误:
Microsoft JScript runtime error: Exception thrown and not caught.
似乎这个问题与 Visual Studio 无关,但特定于 javascript。
例如,我可以在调用$.ajax之前在这个函数中声明一个变量,在error:中赋值,然后在$.ajax调用之后将throw从函数中之后问题...
那么如何以这种方式从嵌套函数中抛出错误呢?如果可能的话,我想在这个函数之外 catch 这个错误。
【问题讨论】:
-
你将无法在函数之外捕获它 - ajax 是异步的。只需返回 ajax 调用的结果(一个 jQuery 延迟对象),并利用 jQuery 的延迟方法
-
有时来自 XMLHttpRequest 的安全错误会避开该请求/周围代码中的错误处理程序。
标签: javascript jquery exception-handling scope