Obs*_*nix 5 c# exception-handling owin asp.net-web-api2
我正在尝试创建一个oWin中间件类,该类将捕获堆栈中的所有异常并进行适当处理。一种
下面这个文章,我创建了一个IExceptionHandler类来传递从的WebAPI异常成中间件堆栈。
但是,这似乎不起作用。尽管该HandleCore方法已被调用并被执行info.Throw(),但该异常从未出现在Middleware类中。
异常处理程序
public class WebApiExceptionPassthroughHandler : ExceptionHandler
{
public override Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
{
HandleCore(context);
return Task.FromResult(0);
}
public override void Handle(ExceptionHandlerContext context)
{
HandleCore(context);
}
private void HandleCore(ExceptionHandlerContext context)
{
//Pass webAPI Exceptions up the stack to the Logging Middleware - which will handle all exceptions.
if (!ShouldHandle(context)) return;
var info = ExceptionDispatchInfo.Capture(context.Exception);
info.Throw();
}
public override bool ShouldHandle(ExceptionHandlerContext context)
{
return context.ExceptionContext.CatchBlock.IsTopLevel;
}
}
Run Code Online (Sandbox Code Playgroud)
启动
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use<LoggingMiddleware>();
GlobalConfiguration.Configure(WebApiConfig.Register);
app.UseWebApi(GlobalConfiguration.Configuration);
}
}
Run Code Online (Sandbox Code Playgroud)
记录中间件
public class LoggingMiddleware : OwinMiddleware
{
public LoggingMiddleware(OwinMiddleware next) : base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
//TODO: Initialise the log
try
{
await Next.Invoke(context);
}
catch (System.Exception ex)
{
//This is not getting reached.
var i = 1;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在webapi.config中,我有以下命令:
config.Services.Replace(typeof(IExceptionHandler), new WebApiExceptionPassthroughHandler());
Run Code Online (Sandbox Code Playgroud)
如何使webApi异常冒泡到中间件日志记录类?
小智 1
如果您想搬到欧文,请摆脱那个坏习惯System.Web,并且GlobalConfiguration。尝试在Startup.
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use<LoggingMiddleware>();
var config = new HttpConfiguration();
//Move your WebApiConfig.Register here
config.Services.Replace(typeof(IExceptionHandler), new WebApiExceptionPassthroughHandler())
//Finally use your newly created config here
app.UseWebApi(config);
}
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你。