• 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();
     
                    }
  • 相关阅读:
    poj 2488 DFS
    畅通工程 并查集模版
    KMP 模板
    poj 1426 DFS
    poj 2528 线段数
    poj 3468 线段数 修改区间(点)
    CVPR2012文章阅读(2)A Unified Approach to Salient Object Detection via Low Rank Matrix Recovery
    如何制定目标
    Saliency Map 最新综述
    计算机视觉模式识别重要会议杂志
  • 原文地址:https://www.cnblogs.com/shanhe/p/4010744.html
Copyright © 2020-2023  润新知