.netcore2.1 封装全局打印异常信息过滤器
- 设置异常信息拦截
public class GlobalExceptionFilter : IExceptionFilter { readonly ILogger _logger; public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger) { _logger = logger; } public void OnException(ExceptionContext context) { _logger.LogError(context.Exception, context.Exception.Message); if (context.Exception is ShowMessageException) { context.Result = new JsonResult(context.Exception.Message); } else { context.Result = new JsonResult("服务器异常"); } context.ExceptionHandled = true; } }
- 定义异常类
public class ShowMessageException : Exception { public ShowMessageException(string message) : base(message) { } }
- 在Startup.cs文件中,注入服务
public void ConfigureServices(IServiceCollection services) { //filters services.AddScoped<GlobalExceptionFilter>(); }