【发布时间】:2023-11-28 04:41:01
【问题描述】:
当我发出一个同步的 jQuery ajax 请求时,我需要能够延迟向用户显示错误消息,直到我可以添加一些在我的错误函数上下文中不存在的更多信息。我正在尝试找到一种方法来抛出收集到的有关异常的信息,以便它可以被捕获到更高的链条上,并向用户显示更有意义的信息。我发现即使使用同步请求,当我在错误函数中放置一个 throw 语句时,我的包装 catch 块也不会捕获它。
function GetFileName(entity, field, guid){
var filename;
try
{
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: myURLwashere,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
async: false,
success: function (data, textStatus, xhr) {
var result = data.d;
filename = result[field];
},
error: function (xhr, textStatus, errorThrown) {
throw textStatus + " " + errorThrown;
//entity, field and guid are null here
}
});
}
catch (err){
//this catch block does not catch the exception thrown by the error function.
throw "Error Getting File Name from web service for entity '" + entity + "' field '" + field + "' and guid '" + guid + "' (" + err.message + ")";
}
return filename;
}
这是一个非常简单的例子。我可以通过几个函数嵌套好几层,并希望在向用户显示之前多次添加到错误消息中。
更新 我更新了问题以反映我的最终目标(嵌套错误处理),而不要求解决方案是同步的,这已被劝阻。
【问题讨论】:
-
这个问题的答案很简单;您根本不应该进行同步 ajax 调用。
-
关于同步请求:从 Gecko 30.0(Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27)开始,由于对用户体验的负面影响,主线程上的同步请求已被弃用。(来自 mdn)。
-
明白。关于如何使用异步请求正确聚合嵌套调用中的良好错误消息的一些建议怎么样?
标签: javascript jquery ajax asynchronous error-handling