• 爱上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,呵呵,这点要清楚.

    感谢各位阅读!

  • 相关阅读:
    grep在一个特定的文件搜索文件夹keyword
    Mysql HA
    通过wmi获取本地硬件信息的一些疑问。
    nginx+tomcat 架构 HttpServletRequest.getScheme()获取正确的协议
    mybatis配置log4j控制台打印SQL语句
    mybatis使用${}拼接sql出错??
    【MySQL】JDBC连接MySQL的一些问题以及解决办法
    mybatis 嵌套查询子查询column传多个参数描述
    关于一些对location认识的误区
    Nginx+lua学习
  • 原文地址:https://www.cnblogs.com/sjqq/p/7529045.html
Copyright © 2020-2023  润新知