我的 OwinMiddleware 中没有捕获异常
Exceptions not caught in my OwinMiddleware
我创建了一个 OwinMiddleware 来捕获我的 api 请求中所有未处理的异常。
public class UnhandledExceptionMiddleware : OwinMiddleware
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public UnhandledExceptionMiddleware(OwinMiddleware next) : base(next)
{ }
public override async Task Invoke(IOwinContext context)
{
try
{
await Next.Invoke(context);
}
catch (Exception ex)
{
logger.Fatal(ex, ex.Message);
}
}
}
但是如果我在我的控制器函数中抛出一些错误,则不会使用 catch 块,并且在这个中间件中似乎一切都很好。为什么我的 catch 块没有被使用?
更新
这是我的 Owin 配置。 Invoke 方法仅适用于 catch 无效
public void Configuration(IAppBuilder app)
{
// Enables use of spatial data types
SqlServerTypes.Utilities.LoadNativeAssemblies(HostingEnvironment.MapPath("~/bin"));
HttpConfiguration config = new HttpConfiguration();
IContainer container = AutoFacConfig.Register(config, app);
app.UseApplicationInsights();
app.UseNLog();
app.Use<UnhandledExceptionMiddleware>();
中间件按照它们添加到管道的顺序被调用。确保在这种情况下 UnhandledExceptionMiddleware
在启动期间先于任何其他添加
public class Startup {
public void Configuration(IAppBuilder app) {
app.Use<UnhandledExceptionMiddleware>();
//...Add other middleware
//...code removed for brevity
}
}
用这个 post 解决了。
您必须覆盖默认的异常过滤器才能在中间件中捕获异常。
我创建了一个 OwinMiddleware 来捕获我的 api 请求中所有未处理的异常。
public class UnhandledExceptionMiddleware : OwinMiddleware
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public UnhandledExceptionMiddleware(OwinMiddleware next) : base(next)
{ }
public override async Task Invoke(IOwinContext context)
{
try
{
await Next.Invoke(context);
}
catch (Exception ex)
{
logger.Fatal(ex, ex.Message);
}
}
}
但是如果我在我的控制器函数中抛出一些错误,则不会使用 catch 块,并且在这个中间件中似乎一切都很好。为什么我的 catch 块没有被使用?
更新
这是我的 Owin 配置。 Invoke 方法仅适用于 catch 无效
public void Configuration(IAppBuilder app)
{
// Enables use of spatial data types
SqlServerTypes.Utilities.LoadNativeAssemblies(HostingEnvironment.MapPath("~/bin"));
HttpConfiguration config = new HttpConfiguration();
IContainer container = AutoFacConfig.Register(config, app);
app.UseApplicationInsights();
app.UseNLog();
app.Use<UnhandledExceptionMiddleware>();
中间件按照它们添加到管道的顺序被调用。确保在这种情况下 UnhandledExceptionMiddleware
在启动期间先于任何其他添加
public class Startup {
public void Configuration(IAppBuilder app) {
app.Use<UnhandledExceptionMiddleware>();
//...Add other middleware
//...code removed for brevity
}
}
用这个 post 解决了。
您必须覆盖默认的异常过滤器才能在中间件中捕获异常。