我正在使用CustomErrorHandler属性来处理我的asp.net mvc应用程序中的错误。代码如下:如何在MVC 3.0中接收并显示JSON错误响应MVC 3.0中的Ajax应用程序
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错误。
在正常误差的情况下,我建立的误差模型,并显示错误观点
,但在阿贾克斯错误的情况下,我想表现出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);
}
@ Oleg ..我正在使用jquery unobstrusive ajax .. –
@ Oleg..it是击中失败的函数..但我无法从中检索错误信息。 –
@Avinash:您使用'data.ErrorMessage'(请参阅您发布的代码)。而不是你应该使用'$ .parseJSON(data.responseText).ErrorMessage'(请参阅我的答案)。 – Oleg