我正在使用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的未定义,而不是显示实际的错误消息。
请帮助/建议如何处理。
Updated2: 这是如何解决的:
function Failed(jqXHR, textStatus, errorThrown) {
var Error = $.parseJSON(jqXHR.responseText);
alert("Sorry,An error occured while processing your request");
alert(Error.ErrorMessage);
}
我发现奇怪的是,您想在Ajax错误的情况下显示一些HTML表单。Ajax请求通常使用jQuery.ajax的.fail()
方法或error
回调来获取错误信息。在回调内部,可以使用解码服务器响应,然后显示一些错误消息,例如或更复杂的对话框。我想您当前代码中的主要问题是因为您没有在代码中设置Ajax请求的情况。var error = $.parseJSON(jqXHR.responseText);
alert(error.ErrorMessage);
filterContext.ExceptionHandled = true;
对您当前的代码做一点说明:我认为您可以安全地使用IsAjaxRequest扩展名(形式为if (filterContext.HttpContext.Request.IsAjaxRequest()) {...}
)而不是测试.Headers["X-Requested-With"]
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句