[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中測試請求,如下圖所示,這樣就說明全局異常已經完成替換了。

三、下一章介紹

swagger的完整接入方法

 
分類:  abpvnext學習


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM