Ich versuche, eine OWin-Middleware-Klasse zu erstellen, die alle Ausnahmen im Stack erfasst und entsprechend behandelt. AGlobal Exception Handler nicht aufgerufen
Nach Artikel this habe ich eine IExceptionHandler
Klasse erstellt, um die Ausnahme von WebApi in den Middleware-Stapel zu übergeben.
Dies scheint jedoch nicht zu funktionieren. Obwohl die HandleCore
-Methode aufgerufen wird und info.Throw()
erreicht wird, wird die Ausnahme nie in der Middleware-Klasse angezeigt.
Exception
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;
}
}
Startup
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use<LoggingMiddleware>();
GlobalConfiguration.Configure(WebApiConfig.Register);
app.UseWebApi(GlobalConfiguration.Configuration);
}
}
LoggingMiddleware
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;
}
}
}
Innen webapi.config, ich habe diesen Befehl ein:
config.Services.Replace(typeof(IExceptionHandler), new WebApiExceptionPassthroughHandler());
Wie erhalte ich die WebAPI Ausnahme zu sprudeln Klasse an die Middleware-Protokollierung?