在jquery ajax错误回调中捕获错误?

我倾向于在我的应用程序中使用大量的jquery ajax调用到服务器端。

通常当服务器端出现问题时,会序列化错误消息并作为响应发送(JSON)。 类似的东西

{ "ErrorMessage" : "Something went wrong: " + ex.message } 

我想知道的是,是否有任何方法可以使错误最终导致jquery ajax error回调,而不是success

有没有办法做到这一点? 或者我应该坚持我以前处理错误的方式? 如果您提供PHP或ASP.NET + c#示例并不重要,因为我对两者都感兴趣。 谢谢

你可以让它们最终出现在jQuery的error callback中。 在ASP.NET中,您需要做的就是将web.config中的custom errors部分更改为 但是如果您选择此路线,请确保将您的Web服务单独放在一个文件夹,以便您只为您的Web服务调用执行此操作而不关闭整个站点; 例如:

       

这样,您的Web方法抛出的任何exception都将在jQuery中的error callback中处理。

您可以让exception传播而不在Web方法上缓存它,也可以捕获它并重新抛出更“用户友好”的消息。

这可以使用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); } );