How to catch ASP.NET Core 2 SignalR exceptions on server-side and handle them on client side with JavaScript? How to catch ASP.NET Core 2 SignalR exceptions on server-side and handle them on client side with JavaScript? asp.net asp.net

How to catch ASP.NET Core 2 SignalR exceptions on server-side and handle them on client side with JavaScript?


Summary

  • I could't and I'm not aware of direct replica

  • but you can use this hack to send the exception

  • for simplicity I didn't use a custom Hub class , but you can.

  • or you can use move it to standalone method

Solution

Hubs\MyHub.cs

public class MyHub : Hub{     public void test_exception()    {        try        {            var x = 0;            var d = 1 / x;        }        catch (Exception ex)        {            // log or extra            Clients.Caller.SendAsync("handle_exception", ex);        }    }}

wwwroot\js\app1.js

"use strict";var connection = new signalR.HubConnectionBuilder().withUrl("/MyHub").build();connection.start();connection.on("handle_exception", function (err) {    if (err.ClassName === "System.DivideByZeroException") {        alert("You need to take a math class 😊");    }});document.getElementById("test_btn")    .addEventListener("click", function (event) {        connection.invoke("test_exception");        event.preventDefault();});

Pages/Index.cshtml

@page<p/><p/><input type="button" id="testExceptionButton" value="TestException" /><script src="~/lib/signalr/dist/browser/signalr.js"></script><script src="~/js/app1.js"></script>

Screenshot

]


Extra :

  • you can add global Server-side logging

    • Logging and diagnostics in ASP.NET Core SignalR | Microsoft Docs

      public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>    WebHost.CreateDefaultBuilder(args)        .ConfigureLogging(logging =>        {            logging.            AddFilter(             "Microsoft.AspNetCore.SignalR",             LogLevel.Debug);            logging.            AddFilter(             "Microsoft.AspNetCore.Http.Connections",             LogLevel.Debug);        })        .UseStartup<Startup>();

Ref.


In order to complement @Mohamed's answer and as per SignalR - Handle errors:

If you want to propagate the error to the client, you can use the HubException class. If you throw a HubException from your hub method, SignalR will send the entire message to the client, although it will include just the exception message, not the inner exception, stack trace or other properties.

public Task ThrowException(){    throw new HubException("This error will be sent to the client!");}