👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
Exception Handling and Logging in SignalR

Exception Handling and Logging in SignalR

signalr

8 Articles

Improve

In this article, let's learn about Exception Handling and Logging in SignalR.

Note: If you have not done so already, I recommend you read the article on Message Pack Hub Protocol and Keep Alive in SignalR.

Table of Contents

  1. Introduction
  2. Exception Handling and Logging
  3. Summary

Introduction

In our previous article we about what are Message Pack Hub Protocol and Keep Alive and how to configure them. Today in this article, lets learn about how to handle errors and log them in SignalR. We will also see how to log messages that are sent and received through the SignalR connection. This is useful for debugging and monitoring the communication between the client.

Exception Handling and Logging

What happens when a hub method is invoked and an exception occurs? So when an exception occurs on the server, the connection will not close. The only thing the hub do is send a message to the client that something went wrong. The client library will detect that and throw the error.

Code Sample - Standard Exception

And to see the exception message, there are two possible solutions. Instead of throwing a standard exception, you could throw a HubException. Now, the message is visible. This is usable when you deliberately want to send an exception message to the client, for example, a data validation error. SignalR will also throw HubExceptions itself when something goes wrong.

Code Sample - Hub Exception

All exceptions that are not HubExceptions thrown on the server will not contain the exception message. But if you always want that message, no matter which exception is thrown, in Program.cs where SignalR is added to DI. Note that just the Exception message is sent to the client, not the stack trace or other exception information. You should be careful turning on EnabledDetailedErrors because this information could also reveal possible attack vectors to your application. Therefore, I recommend not turning this on in production.

Code Sample - SignalR Exception Configuration

To see more logs, Microsoft.AspNetCore.SignalR category is about all activity of hubs like invoking methods. You can also set Microsoft.AspNetCore.Http.Connections to get logging around transports such as which transport was selected and activity around the selected transport.

Summary

In this article, we learnt about Exception Handling and Logging in SignalR. We also saw how to handle exception as Hub Exception. In the next article, we will learn about Streaming and Authentication & Authorization in SignalR.

👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
  • Signalr
  • Exception
  • Error
  • Logging