Unhandled Exception Global Handler for OWIN / Katana?

后端 未结 4 882
深忆病人
深忆病人 2020-12-02 16:47

What is the proper way to implement a global Exception catcher-handler in a Katana (OWIN) implementation?

In a self-hosted OWIN/Katana implementation running as an A

4条回答
  •  独厮守ぢ
    2020-12-02 17:37

    @Khanh TO's answer is excellent; Nice terse code, and well explained.

    It was not working for me. I added a test exception to one of my .NET MVC controllers like this:

    throw new Exception("Test GlobalExceptionMiddleware");
    

    The exception was not caught in the Invoke method.

    This is very easy to debug:

    1. Put a breakpoint on the test exception.
    2. Hit F10 or step over each line until you get to the code that is handling the exception.

    For me, there was code added to a BaseController overriding OnException. This code was handling the exception and not rethrowing. I hope this is a helpful addendum to @Khanh TO's answer.

    Update

    OK, I realize this question is tagged with Web API, and my use case is .NET MVC, but I found this question on a search for Owin middleware. When I debug my solution with the test exception, and watch $exception in the Locals view, the exception is gone when I get back to the Owin middleware. Therefore I have not used the code in @Khanh TO's answer. Instead I have added try/catch blocks to my Startup and Global.asax. I have also OnException in my base controller like this:

    protected override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.ExceptionHandled)
        {
            return;
        }
        var e = filterContext.Exception;
        Log.Error("BaseController.OnException caught exception:", e);
        filterContext.ExceptionHandled = true;
    }
    

    This answer will catch any exceptions on application start up and any exception in a controller. That is enough for my needs.

提交回复
热议问题