Reputation: 4155
I'm attempting to create an oWin middleware class that will capture all exceptions in the stack, and handle them appropriately. A
Following this article, I created an IExceptionHandler
class to pass the exception from WebApi up into the Middleware stack.
However, this does not appear to be working. Although the HandleCore
method is called, and info.Throw()
is hit, the exception never appears inside the Middleware class.
ExceptionHandler
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;
}
}
}
Inside webapi.config, I have this command:
config.Services.Replace(typeof(IExceptionHandler), new WebApiExceptionPassthroughHandler());
How do I get the webApi exception to bubble up to the Middleware logging class?
Upvotes: 5
Views: 1077
Reputation: 153
If you're trying to move to Owin get rid of that bad System.Web
, and GlobalConfiguration
. Try creating you Api config in 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);
}
}
Hope it helps.
Upvotes: 1