1

I have created a OwinMiddleware to catch all unhandled exceptions on my api requests.

 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);
        }
    }
}

But if I throw some error in my controller function the catch block is not used and in this middleware seems that everything is fine. Why my catch block is not used?

UPDATE

Here my Owin Config. The Invoke Method works only the catch is not working

public void Configuration(IAppBuilder app)
    {
        
        // Enables use of spatial data types
        SqlServerTypes.Utilities.LoadNativeAssemblies(HostingEnviron‌​ment.MapPath("~/bin"));

        HttpConfiguration config = new HttpConfiguration();
        IContainer container = AutoFacConfig.Register(config, app);

        app.UseApplicationInsights();
        app.UseNLog();
        app.Use<UnhandledExceptionMiddleware>();
Community
  • 1
  • 1
cpiock
  • 1,275
  • 2
  • 17
  • 44
  • 2
    could be the order it falls in the pipeline.also something that has tripped me up in the past. https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-middleware-in-the-iis-integrated-pipeline – smiggleworth Jan 19 '18 at 12:38
  • Can you show how your are setting up your Owin pipeline? – RikRak Jan 19 '18 at 13:48

2 Answers2

0

Middleware are invoked in the order in which they are added to the pipeline. Make sure that in this case the UnhandledExceptionMiddleware is added before any others during startup

public class Startup {
    public void Configuration(IAppBuilder app) {

        app.Use<UnhandledExceptionMiddleware>();

        //...Add other middleware

        //...code removed for brevity
    }
} 
Nkosi
  • 235,767
  • 35
  • 427
  • 472
0

Solved with this post. Disable *all* exception handling in ASP.NET Web API 2 (to make room for my own)?

You have to ovverride the default IExceptionFilter to catch exceptions in the middleware.

cpiock
  • 1,275
  • 2
  • 17
  • 44