如何从application_error返回AJAX错误函数?

时间:2016-10-17 08:12:38

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

下面的代码最终出现在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");

1 个答案:

答案 0 :(得分:2)

当收到error以外的$.ajax HttpStatusCode时,2xx的{​​{1}}处理程序将被执行。考虑到这一点,您可以返回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 }));
    }
}