Search code examples
c#exceptionasp.net-web-api2owin-middleware

Globally handle all exceptions in WebAPI 2


I am working in WebApi2. I am going to implement global exception handling. As all we knew, we can use IExceptionHandler and IExceptionLogger for the same. I also implemented the same and working fine.

But i am little bit confused with some more scenarios. So I split all my scenarios into 3 parts

1. API Exceptions

Here all exceptions in the bound of API need to be handled. Of course, here the rescue is IExceptionHandler and IExceptionLogger interfaces. We can implement this and can sent custom HttpResponseMessage from the handler

2. Owin Pipeline Exceptions

Here all exception in the owin middleware like token api and all Auth provider level errors.

I read about custom exceptions for middle ware also. But here i need clear suggestion for best practice.

Is this good to create custom middle ware exception or handle in Global.asax?

3. Any other Exceptions other than Specified

Here any other exceptions not mentioned above. I don't know exactly, is any other exceptions possible here but i am just thinking about that. If yes, how we need to handle?

Only option is Global.asax Application_Error event. But from this how can i response as HttpResponseMessage with my custom model.

Please give your comments and better way to handle all these exceptions.

Objective : Client didn't get any 500 error with full stack trace. All exceptions will be handled and sent only my custom message to the client

Questions : How to handle owin pipeline errors and any errors which are not handled in point 1 ?


Solution

  • for handling Owin pipeline exception you can write your own ExceptionHandler Middleware and add it to the begining of your owin pipeline. Your middleware can be like this

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

    and also you should write exception handling in Application_Error in case of an exception happened in your handling login in GlobalExceptionMiddleware.

    In global.asax in Application_Error you can use Response.Write(JsonConvert.SerializeObject(yourObject) to return your custom error.

    And also there's no global.asax on selfhost so the advantage of having GlobalExceptionMiddleware is that if you ever decide to use SelfHost instead of IIS, all your exceptions are handled.