(一)mvc异常过滤器限制(限定action范围内)
异常过滤器IExceptionFilter ( A filter that runs after an action has thrown an System.Exception.),顾,它抓取的范围是Action方法执行过程中出现的未处理的异常,其它异常并不会被该过滤器捕捉到,如身份验证器中的异常,所以用IExceptionFilter做全局异常抓取是有很大局限性的
(二)UseExceptionHandler中间件
在Configure中注册UseExceptionHandler处理全局未处理异常,该模块可分成两部分,1.开发环境(可打印详细异常) 2.生产环境(返回自定义数据),具体实现如下
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider svp)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(builder => builder.Run(async context => await ErrorEvent(context)));
}
}
public Task ErrorEvent(HttpContext context)
{
var feature = context.Features.Get<IExceptionHandlerFeature>();
var error = feature?.Error;
LogHelper.Write("Global\\Error", error.Message, error.StackTrace);
return context.Response.WriteAsync(JsonHelper.ToJson(new RequestResult(444, "系统未知异常,请联系管理员")), Encoding.GetEncoding("GBK"));
}
该方法可抓取全局未处理异常,ErrorEvent方法内可根据个人需要自定义逻辑处理,该方法内有两部分需要注意,1.异常信息获取部分
var feature = context.Features.Get<IExceptionHandlerFeature>();
var error = feature?.Error;
2.返回数据是自定义编码部分,.netcore 使用gbk编码是需要提前注册的,我习惯在Program.cs main方法下直接先进行注册,注册之后才能正常使用,否则该部分会抛异常
public static void Main(string[] args)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
BuildWebHost(args).Run();
}
注册后可正常使用