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();
     
                    }
  • 相关阅读:
    大数据学习路线图 让你精准掌握大数据技术学习
    在AI人工智能中如何巧妙学习大数据编程,成为五十万年薪的佼佼者
    大数据学习之Hadoop快速入门
    大数据学习|小白学习大数据需要满足这六个条件你就能学好大数据
    大数据学习路线(自己制定,从零开始)
    大数据学习之路(跟着大神学习一波)
    为什么这么多人学习大数据?新手该如何上手大数据?
    大数据学习路线图 让你精准掌握大数据技术学习?
    [监督学习]GDA 高斯判别分析
    The Josephus problem
  • 原文地址:https://www.cnblogs.com/shanhe/p/4010744.html
Copyright © 2011-2022 走看看