SignalR, Owin and exception handling

前端 未结 2 1923
时光说笑
时光说笑 2021-01-04 04:24

I\'ve developed a sample SignalR application based on ASP.NET 4.5 & Owin, and I\'ve hosted that app on IIS 7.5.

Everything is working fine, but how can I handle

2条回答
  •  攒了一身酷
    2021-01-04 04:38

    The answer by @halter73 is great for errors thrown inside hubs, but it doesn't catch errors thrown during their creation.

    I was getting the exception:

    System.InvalidOperationException: 'foobarhub' Hub could not be resolved.

    The server was returning an HTML page for this exception, but I needed it in JSON format for better integration with my Angular app, so based on this answer I implemented an OwinMiddleware to catch exceptions and change the output format. You could use this for logging errors instead.

    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)
            {
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = 500;
    
                await context.Response.WriteAsync(JsonConvert.SerializeObject(ex));
            }
        }
    
    }
    

    Add the registration in OwinStartup.cs, just remember to place it before the MapSignalR method call:

    public class OwinStartup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Use(); // must come before MapSignalR()
    
            app.MapSignalR();
        }
    }
    

提交回复
热议问题