WebEnh

.net7 mvc jquery bootstrap json 学习中 第一次学PHP,正在研究中。自学进行时... ... 我的博客 https://enhweb.github.io/ 不错的皮肤:darkgreentrip,iMetro_HD
随笔 - 1079, 文章 - 1, 评论 - 75, 阅读 - 174万
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

[Abp vNext 入坑分享] - 5.全局异常替换

Posted on   WebEnh  阅读(1315)  评论(0编辑  收藏  举报

一、简要说明

【项目源码】

【章节目录】

  前面我们已经初步完成了框架的功能了,jwt的也已经接入完成了。
  现在需要进行全局异常的接入了,abpvnext官方本来就有了全局异常的模块了,介绍链接。但是我自己感觉那个并不是很符合我自己的开发标准,因此需要替换掉他们的异常处理,变成由我们自己输出的形式,且记录日志。
  替换之前,首先我们需要知道的是在netcore中,若要定义自己的异常filter是需要继承IExceptionFilter的,并在Starup里面去注入。因此AbpExceptionFilter也是继承IExceptionFilter的。因此它也属于filter中的一种。其次netcore项目中,filter是可以通过MvcOptions中的options.Filters去获取到所有的注入的filter的。因此我们需要把AbpExceptionFilter找出来,并移除,然后再添加我们自己注入的ExceptionFilter就可以了。具体看以下步骤吧:

二、具体步骤

2.1、 首先我们在Host的Module中的ConfigureServices里面添加以下的代码把AbpExceptionFilter从filter中找出来,然后移除:

 Configure<MvcOptions>(options =>
            {
                var index = options.Filters.ToList().FindIndex(filter => filter is ServiceFilterAttribute attr && attr.ServiceType.Equals(typeof(AbpExceptionFilter)));
                if (index > -1)
                    options.Filters.RemoveAt(index);
            });

2.2、 定义好我们的LeanGlobalExceptionFilter并继承IExceptionFilter,实现相应的方法,如下:

public class LeanGlobalExceptionFilter: IExceptionFilter
    {
        private readonly ILogger<LeanGlobalExceptionFilter> logger;

        public LeanGlobalExceptionFilter( ILogger<LeanGlobalExceptionFilter> logger)
        {
            this.logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            logger.LogError(new EventId(context.Exception.HResult),
                context.Exception,
                context.Exception.Message);
            context.Result = new JsonResult(new{ code = 500, err = "系统异常" });
            context.ExceptionHandled = true;
        }
    }

2.3、回到Host的Module中,在除去AbpExceptionFilter的后面添加我们自己的filter,如下

 Configure<MvcOptions>(options =>
            {
                var index = options.Filters.ToList().FindIndex(filter => filter is ServiceFilterAttribute attr && attr.ServiceType.Equals(typeof(AbpExceptionFilter)));
                if (index > -1)
                    options.Filters.RemoveAt(index);
                options.Filters.Add(typeof(LeanGlobalExceptionFilter));
            });

2.4、这样我们就添加好自己的全局异常的filter了,下面让我们来试一下是否替换成功了。添加好异常代码int ssss = int.Parse("aaaaa");
跑起项目,在swagger中测试请求,如下图所示,这样就说明全局异常已经完成替换了。

三、下一章介绍

swagger的完整接入方法

 
编辑推荐:
· 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框架的用法!
点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

了解更多