【问题标题】:Catch errors in jquery ajax error callback?在 jquery ajax 错误回调中捕获错误?
【发布时间】:2012-05-14 19:22:43
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: c# php jquery asp.net ajax


    【解决方案1】:

    您可以让它们在 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>
    

    这样,在您的网络方法上抛出的任何异常都将在 jQuery 中的 error callback 中处理。

    您可以让异常传播而不将其缓存在您的网络方法中,或者您可以捕获它并重新抛出更“用户友好”的消息。

    【讨论】:

    • 好吧,但我想错误将作为 asp.net 默认错误页面作为 HTML 而不是 JSON 返回?
    • request, status, error 将作为 JSON 对象返回。您可以在错误处理程序中执行以下操作:alert(request.responseText);。见这里:stackoverflow.com/questions/377644/…
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-22
      • 2019-03-02
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      • 2010-10-27
      • 2012-06-20
      相关资源
      最近更新 更多