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
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();
}
}