How to override default unhandled exception output in Owin?

前端 未结 2 1009
走了就别回头了
走了就别回头了 2021-01-04 10:41

I\'ve written simple server using Owin Self-hosting and WebApi:

namespace OwinSelfHostingTest
{
    using System.Threading;
    using System.Web.Http;
    us         


        
相关标签:
2条回答
  • 2021-01-04 11:14

    When you await a async method, an exception won't be thrown into the caller's context, but will be available by inspecting the task returned to the caller.

    So, with this modification to the solution provided by @yuval-itzchakov you'll be able to capture underlying exceptions:

    var subtask = Next.Invoke(context);
    
    await subtask;
    
    if (subtask.Exception != null)
    {
        // log subtask.Exception here
    }
    
    0 讨论(0)
  • 2021-01-04 11:16

    You do so by creating an OWIN MiddleWare and hooking it into the pipeline:

    public class CustomExceptionMiddleware : OwinMiddleware
    {
       public CustomExceptionMiddleware(OwinMiddleware next) : base(next)
       {}
    
       public override async Task Invoke(IOwinContext context)
       {
          try
          {
              await Next.Invoke(context);
          }
          catch(Exception ex)
          {
              // Custom stuff here
          }
       }
     }
    

    And hook it on startup:

    public class Startup
    {
        public void Configuration(IAppBuilder builder)
        {
            var config = new HttpConfiguration();
    
            config.Routes.MapHttpRoute(
                "Default",
                "{controller}/{id}",
                new { id = RouteParameter.Optional }
                );
    
            builder.Use<CustomExceptionMiddleware>().UseWebApi(config);
        }
    }
    

    That way any unhandled exception will be caught by your middleware and allow you to customize the output result.

    An important thing to note: if the thing being hosted has an exception handling logic of it's own, as WebAPI does, exceptions will not propagate. This handler is meant for any exception which goes by unhandeled by the underlying service being hosted.

    0 讨论(0)
提交回复
热议问题