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

MVC抛出自定义异常,并易Json方式返回

时间:2017-10-13 13:56:11      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:width   raw   style   错误   size   dia   ror   ajax   ons   

相关链接

 

优点:

  可以统一处理所有页面的异常,对所有需要返回json数据的异常,都用同样的方法throw new DVMException()。页面展示,controller的错误处理方式一样

  节省编码时间,不用针对每一个controller编写错误json

  throw new DVMException()可以不仅出现在调用层级更深的其他方法中

  编码格式统一

 

 

 

自定义Exception:

    /// <summary>
    /// NewCRM异常
    /// </summary>
    public class DVMException : Exception
    {
        /// <summary>
        /// 操作结果
        /// </summary>
        public OPResult Result { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="opr">操作结果</param>
        /// <param name="message">消息内容</param>
        public DVMException(OPResult opr, String message)
            : base(message)
        {

            Result = opr;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="opr">返回代码</param>
        /// <param name="message">错误消息</param>
        /// <param name="e">原始异常</param>
        public DVMException(OPResult opr, String message, Exception e)
            : base(message, e)
        {
            Result = opr;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="message">消息内容</param>
        /// <param name="e">异常栈</param>
        public DVMException(String message, Exception e)
            : base(message, e)
        {
            Result = OPResult.ServerError;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="e">异常堆栈</param>
        public DVMException(Exception e)
            : base("Server Operation Failed", e)
        {
            Result = OPResult.ServerError;
        }
    }

    /// <summary>
    /// 操作结果
    /// </summary>
    public class DVMOPResult
    {
        /// <summary>
        /// 操作是否成功
        /// </summary>
        public Boolean OPSucess { get; set; }
        /// <summary>
        /// 结果代码
        /// </summary>
        public OPResult OPCode { get; set; }
        /// <summary>
        /// 操作结果,类型可变,由Type进行判断
        /// </summary>
        public Object ResultContent { get; set; }
        /// <summary>
        /// 返回类型名称
        /// </summary>
        public String Type { get; set; }

        /// <summary>
        /// 返回是否为数组
        /// </summary>
        public Boolean IsArray { get; set; }
    }

  

自定义HandleErrorAttribute

     public class HandleJsonExceptionAttribute:HandleErrorAttribute
    {
         public override void OnException(ExceptionContext filterContext)
        {
            var logger = IocFactory.Instance.GetInstance<ILogBase>();
            var exception = filterContext.Exception;
            var url = filterContext.HttpContext.Request.RawUrl;
            String message = exception.Message;
            logger.Error(String.Format("Request error on url {0}: {1}", url, message), exception);
            JsonResult jsonResult = new JsonResult() { MaxJsonLength = Int32.MaxValue };
            jsonResult.Data = message;
            filterContext.Result = jsonResult;
            filterContext.ExceptionHandled = true;
        }
    }

 

 

controller中使用:[HandleJsonException]

        [HttpPost]
        [HandleJsonException]
        public ActionResult Save(SaveAccountRequest request)
        {
            var accountDTO = request as AccountDTO;
            FixRatePost(ref accountDTO);
            request.UserId = this.CurrentUser.UserId;
            var id =_accountService.SaveAccount(request);
            if (id < 0)
            {
                throw new DVMException(OPResult.ServerError, "此账户已存在并启用,无法重复创建");
            }
            return new JsonResult { Data = true };
        }

  

 

View展示异常:ajax的error处理

         postCreation: function (successMessage) {
                $.ajax({
                    data: $("form").serialize(),
                    url: "@Url.Content("~/Account/Save")",
                    type: ‘POST‘,
                    dataType: ‘json‘,
                    cache: false,
                    success: function (data) {
                        if (data.toString() == "true") {
                            $.Dialog({
                                overlay: true,
                                shadow: true,
                                flat: false,
                                icon: ‘‘,
                                width: 330,
                                content: ‘<div class="" style="text-align:left;padding:10px;font-size:16px;">‘ + successMessage + ‘</div>‘
                                        + ‘<div class="size4 text-right">‘
                                            + ‘<button class="warning" id="comfirm"><i class="icon-checkmark on-left"></i>关闭</button> ‘
                                        + ‘</div>‘,
                                overlayClickClose: false,
                                onShow: function (_dialog) {
                                    $("#comfirm", $(_dialog)).click(function () {
                                        //保存成功返回列表页
                                        $("#cancel").click();
                                    })
                                }
                            });
                        } else {
                            showAlert(data);
                        };
                        freezeButton(false);
                    },
                    error: function (data) {
                        showAlert(data);
                        freezeButton(false);
                    }
                });
            }

  

  

 

MVC抛出自定义异常,并易Json方式返回

标签:width   raw   style   错误   size   dia   ror   ajax   ons   

原文地址:http://www.cnblogs.com/panpanwelcome/p/7660383.html

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