I do not understand something related to Owin middleware and how ht exceptions are propagated:
In the startup class I have this code:
public static void Configuration(IAppBuilder app)
{
app.Use<DebugMiddleware>();
app.Use(async (ctx, next) =>
{
Debug.WriteLine("Incoming request 1: " + ctx.Request.Path);
await next();
Debug.WriteLine("Outgoing request 1: " + ctx.Request.Path);
});
app.Use(async (ctx, next) =>
{
Debug.WriteLine("Incoming request 2: " + ctx.Request.Path);
await next();
Debug.WriteLine("Outgoing request 2: " + ctx.Request.Path);
});
app.Use(async (ctx, next) =>
{
Debug.WriteLine("Incoming request 3: " + ctx.Request.Path);
await ctx.Response.WriteAsync("<html><head></head><body>Hello World</body></html>");
await next();
Debug.WriteLine("Outgoing request 3: " + ctx.Request.Path);
});
app.Use(async (ctx, next) =>
{
Debug.WriteLine("Incoming request 4: " + ctx.Request.Path);
//throw new Exception("New Exception thrown");
Debug.WriteLine("Outgoing request 4: " + ctx.Request.Path);
});
}
With the DebugMiddleware class looking like this:
public class DebugMiddleware : OwinMiddleware
{
public DebugMiddleware(OwinMiddleware next) : base(next) { }
public override async Task Invoke(IOwinContext context)
{
try
{
Debug.WriteLine("Incoming request DebugMiddleware: " + context.Request.Path);
await Next.Invoke(context);
Debug.WriteLine("Outgoing request DebugMiddleware: " + context.Request.Path);
}
catch (Exception ex)
{
Debug.WriteLine("Catch exception in DebugMiddleware: " + ex.Message);
}
}
}
When I call it I receive something like this, that is ok:
Incoming request DebugMiddleware: /
Incoming request 1: /
Incoming request 2: /
Incoming request 3: /
Outgoing request 3: /
Outgoing request 2: /
Outgoing request 1: /
Outgoing request DebugMiddleware: /
If I throw an exception in the last middleware, it gets caught and handled in the DebugMiddleware:
Incoming request DebugMiddleware: /
Incoming request 1: /
Incoming request 2: /
Incoming request 3: /
Catch exception in DebugMiddleware: New Exception thrown
If I add an ApiController and throw an exception, this is not caught anymore in the DebugMiddleware:
[RoutePrefix("api")]
public class TestApiController : ApiController
{
[Route("test")]
[HttpGet]
public IHttpActionResult Test()
{
throw new Exception("Exc - Test");
}
}
This is what I see:
Incoming request DebugMiddleware: /api/test
Incoming request 1: /api/test
Incoming request 2: /api/test
Incoming request 3: /api/test
Exception thrown: 'System.Exception' in Owin.Demo.dll
An exception of type 'System.Exception' occurred in Owin.Demo.dll but was not handled in user code
Exc - Test
Outgoing request 3: /api/test
Outgoing request 2: /api/test
Outgoing request 1: /api/test
Outgoing request DebugMiddleware: /api/test
Is there a way to catch all handled exceptions from the controller in an exception middleware?