zoukankan      html  css  js  c++  java
  • 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();
     
                    }
  • 相关阅读:
    jQuery中添加自定义或函数方法
    一定要明白采取是哪种提交方式,表…
    基本数据类型
    python之运算符
    Java之递归
    【偏序问题】三维偏序,四维偏序
    【复习笔记】主席树
    【bzoj1901】dynamic ranking(带修改主席树/树套树)
    【bzoj4530】大融合(LCT的子树维护)
    POJ1008 Maya Calendar
  • 原文地址:https://www.cnblogs.com/shanhe/p/4010744.html
Copyright © 2011-2022 走看看