分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

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

发布时间:2023-09-06 01:09责任编辑:董明明关键词: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,呵呵,这点要清楚.

感谢各位阅读!

回到目录

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

原文地址:http://www.cnblogs.com/lori/p/7490659.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved