对于业务层的程序的致命错误,我们一直的做法就是直接抛出指定的异常,让程序去终断,这种做法是对的,因为如果一个业务出现了致命的阻塞的问题,就没有必要再向上一层一层的返回了,但这时有个问题,直接抛异常,意味着服务器直接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,呵呵,这点要清楚.
感谢各位阅读!
标签:
asp.net mvc
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!