My code below ends up in the AJAX success
function. Why? It should execute the error
function. What am I doing wrong?
下面的代码以AJAX success函数结尾。为什么?它应该执行错误函数。我做错了什么?
$.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");
1 个解决方案
#1
2
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:
$的错误处理程序。当接收到除2xx以外的任何内容的HttpStatusCode时,将执行ajax。考虑到这一点,您可以返回500个内部服务器错误,如下所示:
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 }));
}
}
#1
2
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:
$的错误处理程序。当接收到除2xx以外的任何内容的HttpStatusCode时,将执行ajax。考虑到这一点,您可以返回500个内部服务器错误,如下所示:
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 }));
}
}