我倾向于在我的应用程序中对服务器端使用大量的jquery ajax调用。
通常当服务器端出现问题时,会序列化错误消息并作为响应发送(JSON)。类似于
的东西 { "ErrorMessage" : "Something went wrong: " + ex.message }
我想知道的是,如果有任何方法可以在jquery ajax error
回调中结束错误,而不是success
。
有没有办法做到这一点?或者我应该坚持我以前处理错误的方式?如果您提供PHP或ASP.NET + c#示例并不重要,因为我对两者都感兴趣。感谢
答案 0 :(得分:3)
你可以让它们最终出现在jQuery的error callback
上。在ASP.NET中,您需要做的就是将web.config中的custom errors
部分更改为<customErrors mode="Off" />
但,如果您选择此路线,请确保放置您的Web服务位于一个单独的文件夹中,这样您只需为您的Web服务调用执行此操作,而无需关闭整个站点;例如:
<location Path="/Services"> <!--Your web service lives here -->
<system.web>
<customErrors mode="Off" />
</system.web>
</location>
这样,您的Web方法抛出的任何异常都将在jQuery中的error callback
中处理。
您可以让异常传播而不在Web方法上缓存它,或者您可以捕获它并重新抛出更“用户友好”的消息。
答案 1 :(得分:0)
使用jQuery 1.5+中的Deferred
对象是可行的。 Ben Nadel有一些关于这方面的例子,你可以看看http://www.bennadel.com/blog/2255-Using-jQuery-s-Pipe-Method-To-Change-Deferred-Resolution.htm和http://www.bennadel.com/blog/2123-Using-Deferred-Objects-In-jQuery-1-5-To-Normalize-API-Responses.htm
以下是其JavaScript代码的简化版
var request = $.ajax({
type: "post",
url: "./web_service.cfm",
dataType: "json"
});
request = request.pipe(
// Filter the SUCCESS responses from the API.
function (response) {
// real success
if (response.success) {
return (response);
}
else {
// The response is actually a FAIL even though it
// came through as a success (200). Convert this
// promise resolution to a FAIL.
return (
$.Deferred().reject(response)
);
}
},
// Filter the FAIL responses from the API.
function (response) {
return ({
success: false,
data: null,
errors: ["Unexpected error: " + response.status + " " + response.statusText]
});
}
);
// Now that our API response has been filtered, let's attach
// our success and fail handlers to the promise resolution.
request.then(
function (response) {
console.log("Success!!!", response);
},
function (response) {
console.log("Fail!!!", response);
}
);