Ajax+MVC异常错误返回

加入特性
//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
                };
            }
 
        }
    }
 
//Controller
 [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();
 
                }

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。