爱上MVC~业务层刻意抛出异常,全局异常的捕获它并按格式返回

回到目录

对于业务层的程序的致命错误,我们一直的做法就是直接抛出指定的异常,让程序去终断,这种做法是对的,因为如果一个业务出现了致命的阻塞的问题,就没有必要再向上一层一层的返回了,但这时有个问题,直接抛异常,意味着服务器直接500了,前端如何去显示,或者如果你是API的服务,如果为前端返回,如果是500,那直接就挂了,哈哈!

下面是在MVC环境下优化的全局异常捕获代码(非API)

    /// <summary>
    /// 全局异常捕获
    /// </summary>
    public class GlobalExceptionFilterAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            JsonResult response = new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
            if (context.Exception is ArgumentException)
            {
                var exception = (ArgumentException)context.Exception;
                response.Data = new
                {
                    statusCode = System.Net.HttpStatusCode.InternalServerError,
                    errorcode = "02",
                    message = exception.Message,
                };
            }
            else if (context.Exception is Exception)
            {
                var exception = (Exception)context.Exception;
                response.Data = new
                {
                    statusCode = System.Net.HttpStatusCode.InternalServerError,
                    errorcode = "01",
                    message = exception.Message,
                };
            }
            else
            {

                response.Data = new
                {
                    statusCode = System.Net.HttpStatusCode.InternalServerError,
                    errorcode = "03",
                    message = "其它异常",
                };
            }

            context.Result = response;
            context.ExceptionHandled = true;
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.TrySkipIisCustomErrors = true;
        }


    }

如果业务层有问题,直接就throw了

   if (id == 0)
        throw new ArgumentException("id不能为0");
   if (id < 0)
        throw new ArgumentException("id不能是负数");

然后页面后,故意让它抛出异常,我们看一下页面响应的结果

事实上,对于服务器来说,它是200,正常返回的,而对不业务模块来说,它的状态是个500,呵呵,这点要清楚.

感谢各位阅读!

回到目录

 

posted @ 2017-09-07 16:59  张占岭  阅读(1751)  评论(5编辑  收藏  举报