概念
異常過濾器是一種可以在 WebAPI 中捕獲那些未得到處理的異常的過濾器,要想創建異常過濾器,你需要實現 IExceptionFilter 接口,不過這種方式比較麻煩,更快捷的方法是直接繼承 ExceptionFilterAttribute 並重寫里面的 OnException()
方法即可,這是因為 ExceptionFilterAttribute 類本身就實現了 IExceptionFilter 接口
全局
XXX.Common項目下新建自定義異常類:新建文件夾【Custom】新建類:BusinessException.cs【名字自己定義】
using System;
namespace Jwt.Common.Custom
{
/// <summary>
/// 業務異常
/// </summary>
public class BusinessException : Exception
{
public BusinessException(string message) : base(message)
{
}
}
}
WebApi項目下新建文件夾【Custom/Exception】,在Exception文件夾下新建類:CustomExceptionFilterAttribute
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Configuration; using Test.Common.Custom; namespace Test.WebApi.Custom.Exception { public class CustomExceptionFilterAttribute : ExceptionFilterAttribute { private readonly IConfiguration _configuration; public CustomExceptionFilterAttribute(IConfiguration configuration) { _configuration = configuration; } public override void OnException(ExceptionContext context) { #region 自定義異常 if (context.Exception.GetType() == typeof(BusinessException)) { ResponseDto response = new ResponseDto() { Success = false, Message = context.Exception.Message }; context.Result = new JsonResult(response); } #endregion #region 捕獲程序異常,友好提示 else { ResponseDto response = new ResponseDto() { Success = false, Message = "服務器忙,請稍后再試" }; if (_configuration["AppSetting:DisplayExceptionOrNot"] == "1") { response.Message = context.Exception.Message; } context.Result = new JsonResult(response); } #endregion } } }
Startup中注冊
options.Filters.Add<CustomExceptionFilterAttribute>();
縮小粒度到 Controller 或者 Action 級別
[DatabaseExceptionFilter] public class EmployeesController : ApiController { //Some code } [CustomExceptionFilter] public IEnumerable<string> Get() { throw new DivideByZeroException(); }