【问题标题】:How to return to AJAX error function from application_error?如何从 application_error 返回 AJAX 错误函数?
【发布时间】:2017-02-26 03:28:31
【问题描述】:

我下面的代码最终出现在 AJAX success 函数中。为什么?它应该执行error 函数。我究竟做错了什么?

$.ajax({
    url: url,
    type: "POST",
    data: data,
    contentType: "application/json; charset=utf-8",
    success: function(data) {
        if (callback)
            callback(data);

        $.LoadingOverlay("hide");
    },
    error: function (event, jqxhr, settings, thrownError) {
        var t = "";

    }
});
protected void Application_Error(object sender, EventArgs e)
{
    var ctx = HttpContext.Current;

    var exception = ctx.Server.GetLastError();

    bool isAjaxCall = string.Equals("XMLHttpRequest", Context.Request.Headers["x-requested-with"], StringComparison.OrdinalIgnoreCase);
    Context.ClearError();
    if (isAjaxCall)
    {
        //Context.Response.ContentType = "application/json";
        Context.Response.StatusCode = 200;
        Context.Response.Write(
            new JavaScriptSerializer().Serialize(
                new { error = exception.Message }
            )
        );
    }
}

控制器只是抛出一个异常:

throw new Exception("faulty");

【问题讨论】:

    标签: jquery ajax asp.net-mvc asp.net-mvc-5


    【解决方案1】:

    $.ajaxerror 处理程序在收到 2xx 以外的任何 HttpStatusCode 时执行。考虑到这一点,您可以返回 500 Internal Server Error,如下所示:

    protected void Application_Error(object sender, EventArgs e)
    {
        var ctx = HttpContext.Current;
        var exception = ctx.Server.GetLastError();
        bool isAjaxCall = string.Equals("XMLHttpRequest", Context.Request.Headers["x-requested-with"], StringComparison.OrdinalIgnoreCase);
        Context.ClearError();
    
        if (isAjaxCall)
        {
            Context.Response.StatusCode = 500; // note the change here
            Context.Response.Write(new JavaScriptSerializer().Serialize(new { error = exception.Message }));
        }
    }
    

    【讨论】:

    • 从其他人那里复制代码时,我没有注意到 200 状态码:(。谢谢!
    猜你喜欢
    • 2021-04-26
    • 1970-01-01
    • 2021-05-30
    • 2023-04-09
    • 2012-01-08
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    相关资源
    最近更新 更多