Unhandled Exception Global Handler for OWIN / Katana?

Try writing a custom middleware and placing it as the first middleware:

public class GlobalExceptionMiddleware : OwinMiddleware
{
   public GlobalExceptionMiddleware(OwinMiddleware next) : base(next)
   {}

   public override async Task Invoke(IOwinContext context)
   {
      try
      {
          await Next.Invoke(context);
      }
      catch(Exception ex)
      {
          // your handling logic
      }
   }
 }

Place it as the first middleware:

public class Startup
{
    public void Configuration(IAppBuilder builder)
    {
        var config = new HttpConfiguration();

        builder.Use<GlobalExceptionMiddleware>();
        //register other middlewares
    }
}

When we register this middleware as the first middle, any exceptions happening in other middlewares (down the stacktrace) will propagate up and be caught by the try/catch block of this middleware.

It’s not mandatory to always register it as the first middleware, in case you don’t need global exception handling for some middlewares, just register these middlewares before this one.

public class Startup
{
    public void Configuration(IAppBuilder builder)
    {
        var config = new HttpConfiguration();

        //register middlewares that don't need global exception handling. 
        builder.Use<GlobalExceptionMiddleware>();
        //register other middlewares
    }
}

Leave a Comment