天天看點

[Abp vNext 入坑分享] - 5.全局異常替換

一、簡要說明

【項目源碼】

【章節目錄】

  前面我們已經初步完成了架構的功能了,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中測試請求,如下圖所示,這樣就說明全局異常已經完成替換了。

[Abp vNext 入坑分享] - 5.全局異常替換
[Abp vNext 入坑分享] - 5.全局異常替換

三、下一章介紹

swagger的完整接入方法