Ra3IDeN Ra3IDeN - 1 month ago 8
Ajax Question

How to return to AJAX error function from application_error?

My code below ends up in the AJAX

success
function. Why? It should execute the
error
function. What am I doing wrong?

$.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 }
)
);
}
}


The controller simply throws an exception:

throw new Exception("faulty");

Answer

The error handler of $.ajax is executed when a HttpStatusCode of anything other than 2xx is received. With that in mind, you could return a 500 Internal Server Error, like this:

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 }));
    }
}
Comments