码迷,mamicode.com
首页 > Web开发 > 详细

Ajax+MVC异常错误返回

时间:2014-10-08 14:40:55      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   io   ar   sp   div   c   on   

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

Ajax+MVC异常错误返回

标签:style   http   color   io   ar   sp   div   c   on   

原文地址:http://www.cnblogs.com/shanhe/p/4010744.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!