您可以在 Global.asax 中编写一个全局异常处理程序,它将拦截 AJAX 请求期间发生的错误并将它们序列化为响应的 JSON 对象,以便您的客户端错误回调可以提取必要的信息:
protected void Application_Error(object sender, EventArgs e)
{
if (new HttpRequestWrapper(Request).IsAjaxRequest())
{
var exception = Server.GetLastError();
Response.Clear();
Server.ClearError();
Response.ContentType = "application/json";
var json = new JavaScriptSerializer().Serialize(new
{
// TODO: include the information about the error that
// you are interested in => you could also test for
// different types of exceptions in order to retrieve some info
message = exception.Message
});
Response.StatusCode = 500;
Response.Write(json);
}
}
接着:
$(document).ajaxError(function (event, request, settings) {
try {
var obj = $.parseJSON(request.responseText);
alert(obj.message);
} catch(e) { }
});