我正在使用 CustomErrorHandler 属性来处理我的 asp.net mvc 应用程序中的错误。代码如下:
public class CustomHandleErrorAttribute : HandleErrorAttribute // Error handler
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
{
return;
}
if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
{
return;
}
if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
{
return;
}
// if the request is AJAX return JSON else view.
if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
filterContext.Result = AjaxError(filterContext.Exception.Message, filterContext);
}
else
{
filterContext.ExceptionHandled = true;
var controllerName = (string)filterContext.RouteData.Values["controller"];
var actionName = (string)filterContext.RouteData.Values["action"];
var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
filterContext.Result = new ViewResult
{
ViewName = View,
MasterName = Master,
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
TempData = filterContext.Controller.TempData
};
}
}
protected JsonResult AjaxError(string message, ExceptionContext filterContext)
{
if (String.IsNullOrEmpty(message))
message = "Something went wrong while processing your request. Please refresh the page and try again.";
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
return new JsonResult { Data = new { ErrorMessage = message }, ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
}
它具有捕获正常错误和 Ajax 错误的能力。
如果出现正常错误,我正在构建错误模型并显示错误视图
但是,如果出现 Ajax 错误,我想以 JSON 的形式显示错误消息。
我尝试了一些类似的东西:
function Failed(data) { // Onfailed call of MVC Ajax form
alert("Sorry,An error occured while processing your request");
alert(data.ErrorMessage);
}
但是,它表示data.ErrorMessage未定义,而不是显示实际的错误消息。
请帮助/建议如何处理这个问题。
更新2: 这就是它的解决方法:
function Failed(jqXHR, textStatus, errorThrown) {
var Error = $.parseJSON(jqXHR.responseText);
alert("Sorry,An error occured while processing your request");
alert(Error.ErrorMessage);
}