//JsonExceptionFilterAttribute.cs
[ AttributeUsage( AttributeTargets.Method | AttributeTargets .Class)]
public class JsonExceptionFilterAttribute : FilterAttribute,IExceptionFilter
{
public void OnException( ExceptionContext filterContext)
{
if(filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.ExceptionHandled = true;
//关闭IIS自定义错误
filterContext.HttpContext.Response.TrySkipIisCustomErrors =true;
filterContext.Result = new JsonResult
{
Data = new
{
errorMessage = filterContext.Exception.Message
},
JsonRequestBehavior = JsonRequestBehavior .AllowGet
};
}
}
}
[JsonExceptionFilterAttribute ]
//Ajax错误返回部分
error: function (XMLHttpRequest, textStatus, errorThrown) {
try {
var errorJson = {};
//如果不是Json就当HTML字符串处理
if (!XMLHttpRequest.responseText.match("^\{(.+:.+,*){1,}\}$" )) {
//普通字符串处理,
var msg = "";
$(XMLHttpRequest.responseText).each(function (i, item) {
if (item.nodeName.toLocaleLowerCase() == "title" ) {
msg = $(item).text();
}
});
alert(msg);
}
else {
//通过这种方法可将字符串转换为对象
errorJson = $.parseJSON(XMLHttpRequest.responseText);
alert(errorJson.errorMessage);
}
} catch (e) {
alert( "意外的错误" );
}
hidediv();
}