.NET Core通过过滤器和中间件两种方式实现全局异常捕获和日志记录
1.一共有五类过滤器IAsyncAuthorizationFilter IAsyncResourceFilter IAsyncActonFilter IAsyncExceptionFilter IAsyncResultFilter 去掉Async就是同步的
2.注册过滤器 全局注册和Attribute注册 用在特定的Action上
通过过滤器实现全局异常处理
1.建立自己的一个过滤器
public class CustomerExceptionFilter : Attribute, IExceptionFilter
{
private readonly ILogger logger = null;
private readonly IHostingEnvironment environment = null;
public CustomerExceptionFilter(ILogger<CustomerExceptionFilter> logger, IHostingEnvironment environment)
{
this.logger = logger;
this.environment = environment;
} public void OnException(ExceptionContext context)
{
Exception exception = context.Exception;
string error = string.Empty; void ReadException(Exception ex)
{
error += string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, ex.InnerException);
if (ex.InnerException != null)
{
ReadException(ex.InnerException);
}
} ReadException(context.Exception);
logger.LogError(error); ContentResult result = new ContentResult
{
StatusCode = ,
ContentType = "text/json;charset=utf-8;"
}; if (environment.IsDevelopment())
{
var json = new { message = exception.Message, detail = error };
result.Content = JsonConvert.SerializeObject(json);
}
else
{
result.Content = "抱歉,出错了";
}
context.Result = result;
context.ExceptionHandled = true;
}
}
2.添加Nugut包 NLog.Extensions.Logging NLog.Web.AspNetCore ,并在 Startup.cs 文件的 Configure 方法中添加扩展
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory factory)
{
// 将 NLog
factory.AddConsole(Configuration.GetSection("Logging"))
.AddNLog()
.AddDebug(); var nlogFile = System.IO.Path.Combine(env.ContentRootPath, "nlog.config");
env.ConfigureNLog(nlogFile); if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseMvc();
}
3.日志配置文件信息
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" internalLogLevel="info"> <!-- Load the ASP.NET Core plugin -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions> <!-- Layout: https://github.com/NLog/NLog/wiki/Layout%20Renderers -->
<targets>
<target xsi:type="File" name="errorfile" fileName="/data/logs/logfilter/error-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}| ${message} ${exception}|${aspnet-Request-Url}" />
<target xsi:type="Null" name="blackhole" />
</targets> <rules>
<logger name="Microsoft.*" minlevel="Error" writeTo="blackhole" final="true" />
<logger name="*" minlevel="Error" writeTo="errorfile" />
</rules>
</nlog>
4.把这个过滤器注入到容器中
services.AddMvc(
options =>
{
options.Filters.Add(typeof(CustomerExceptionFilter));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
只要请求进入到了MVC中间件中之后抛的异常 都会进到自定义的Filter中
************************
通过中间件实现全局异常处理
1.建立一个自定义的全局异常处理中间件
public class ExceptionMiddleware
{
private readonly RequestDelegate next;
private readonly ILogger logger;
private IHostingEnvironment environment; public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger, IHostingEnvironment environment)
{
this.next = next;
this.logger = logger;
this.environment = environment;
} public async Task Invoke(HttpContext context)
{
try
{
await next.Invoke(context);
var features = context.Features;
}
catch (Exception e)
{
await HandleException(context, e);
}
} private async Task HandleException(HttpContext context, Exception e)
{
context.Response.StatusCode = ;
context.Response.ContentType = "text/json;charset=utf-8;";
string error = ""; void ReadException(Exception ex)
{
error += string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, ex.InnerException);
if (ex.InnerException != null)
{
ReadException(ex.InnerException);
}
} ReadException(e);
if (environment.IsDevelopment())
{
var json = new { message = e.Message, detail = error };
error = JsonConvert.SerializeObject(json);
}
else
error = "抱歉,出错了"; await context.Response.WriteAsync(error);
}
}
2.在管道中加入自定义中间件
app.UseMiddleware<ExceptionMiddleware>();
2.在管道中通过try catch进行异常捕获 这个中间件后面的所有代码都在 try catch里面 只要出发了异常 就会给当前中间件捕获
注意 在某个中间件中发生了异常 但是他抛出的时候 在当前中间件就处理掉了 没有继续往上抛出 这时候就捕获不到
https://www.cnblogs.com/viter/p/10013195.html
.NET Core通过过滤器和中间件两种方式实现全局异常捕获和日志记录的更多相关文章
- 七 异常处理的两种方式(创建全局异常处理器&自定义异常)
1 创建全局异常处理器 实现HandlerExceptionResolve接口 package com.springmvc01; import javax.servlet.http.HttpServl ...
- java程序中抛出异常的两种方式,及异常抛出的顺序
在java中,会经常遇到异常,java提供了两种抛出异常的方式. 方式一: throws ,抛出具体代码中的异常,这种方式编译器都会提示,举例: public static void main(Str ...
- 创建Java多线程的两种方式和线程异常
一.使用多线程的两种方法 使用多线程的两种方法有:继承Thread类和实现runable接口. 二.继承Thread类 来看一下thread类的源代码: class Thread implement ...
- 在.net core中数据操作的两种方式(Db first && Code first)
在开发过程中我们通常使用的是Db first这种模式,而在.net core 中推荐使用的却是 code first 反正我是很不习惯这种开发模式 于是就搜寻整个微软的官方文档,终于找到了有关.net ...
- EntityFramework Core 2.0自定义标量函数两种方式
前言 上一节我们讲完原始查询如何防止SQL注入问题同时并提供了几种方式.本节我们继续来讲讲EF Core 2.0中的新特性自定义标量函数. 自定义标量函数两种方式 在EF Core 2.0中我们可以将 ...
- Spring Boot配置过滤器的两种方式
过滤器(Filter)是Servlet中常用的技术,可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截,常用的场景有登录校验.权限控制.敏感词过滤等,下面介绍下Spring Boot配置过 ...
- .NET MVC中登录过滤器拦截的两种方法
今天给大家介绍两种ASP中过滤器拦截的两种方法. 一种是EF 的HtppModule,另一种则是灵活很多针对MVC的特性类 Attribute 具体什么是特性类可以参考着篇文章:https://www ...
- 国产化之 .NET Core 操作达梦数据库DM8的两种方式
背景 某个项目需要实现基础软件全部国产化,其中操作系统指定银河麒麟,数据库使用达梦V8,CPU平台的范围包括x64.龙芯.飞腾.鲲鹏等.考虑到这些基础产品对.NET的支持,最终选择了.NET Core ...
- Python 实现接口类的两种方式+邮件提醒+动态导入模块+反射(参考Django中间件源码)
实现接口类的两种方式 方式一 from abc import ABCMeta from abc import abstractmethod class BaseMessage(metaclass=AB ...
随机推荐
- ubuntu安装zabbix 3.2(转)
转自:http://www.zabbix.org.cn/viewtopic.php?f=13&t=1096本人略做了写修改. 准备工作 apt-get update apt-get upgra ...
- 个人对stm32ADC编程关键点的理解
平时在做项目或者参加比赛的过程中,个人觉得,有些东西写出来可能会帮助到新手少走弯路.(也很可能是错误的,欢迎大家纠错) 如果只是采集一路信号,直接用ADC独立模式,单通道就可以了. 如果需要同时采集多 ...
- Sublime 个人常用快捷键
Sublime 个人常用快捷键 Hot Key Alt + F3 选中文本所以有相同项;同多次Ctrl + D Ctrl + L 选中整行,继续按可继续选 Ctrl + Shift + M 选择括号内 ...
- href和src的区别(小计)
1.Src 是指向物件的来源地址,请求src资源时会将其指向的资源下载并应用文档中 src的内容是页面上比不可少的一部分,是引入.在 img.script.iframe 等元素上使用. 2.href ...
- Jar包的手动导入
(1)打开项目的file 找到project structure (2)进行以下操作
- ABP 2.0.2 升到 2.2.1
1.选择解决方案 右键 管理 nuget 更新 输入abp 这里只升级 abp的包 点升级 2.update-database 可能需要你添加个迁移(这一步可能不需要) 3.Core 项目下面的Au ...
- JAVA 11初体验
JAVA 11初体验 随着JAVA没半年发布一次新版本,前几天JAVA 11隆重登场.在JAVA 11中,增加了一些新的特性和api, 同时也删除了一些特性和api,还有一些性能和垃圾回收的改进. 作 ...
- DotNetty网络通信框架学习之初识Netty
p{ text-align:center; } blockquote > p > span{ text-align:center; font-size: 18px; color: #ff0 ...
- Excel控制AutoCad进行坐标标注
做过工程测绘,平面设计,使用过Autocad制图的朋友们,都经常要在CAD上标注点或者线的坐标,CAD自身的标注功能,并不能同时标注X和Y坐标,,要同时标注X和Y坐标,可以使用南方CASS软件,或者一 ...
- Windbg程序调试系列4-Live Debugging
上篇博文中给大家分享了使用Windbg分析线程阻塞问题: Windbg程序调试系列3-线程阻塞问题 本篇中我们继续,跟大家分享附加进程实时调试-Live Debugging. 先说一下使用Windbg ...