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