In SignalR v2, I used code like this (below) to handle exceptions that happened when my connections failed. What is the equivalent in SignalR v3? Does SendAsync or SendAsyncCore throw some exception should connections fail or serialization fail?
private async void ManagerOnUserRemoved(UserDto userDto)
{
try
{
await Context.Clients.All.MyFunc(userDto);
}
catch (InvalidOperationException) { }
catch (AggregateException) { }
}
I didn't see any exceptions listed here: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.signalr.client.hubconnectionextensions.sendasync?view=aspnetcore-3.0
Update: I have the same question for the calls from the client-side (to InvokeCoreAsync et al).
In SignalR V3 use HubException to capture exceptions that contain sensitive information, such as connection information.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.signalr.hubexception?view=aspnetcore-3.1
private async void ManagerOnUserRemoved(UserDto userDto)
{
try
{
await Context.Clients.All.MyFunc(userDto);
}
catch(Exception ex) {
//Now check exceptions what you want by exception message or exception code
}
}
With this code you can handle all exceptions, or you can do this:
hubConnection.Error += ex => Console.WriteLine("Error: {0}", ex.Message);
I think it will be help
Related
I am using Apache Ignite 2.7.5.
I don't know whether is there any way is there or not but trying to handle .net thin client exception,but i am not approaching to correct way,how to catch ignite java one throwable exception in c# .net catch block.
code:
public async void loadData(string configPath,List<JObject> dataList)
{
using (var ldr = _ignite.GetDataStreamer<string, Employee>(cacheName))
{
try
{
await ldr.AddData(base64EncodedKey, emp);//from this line i am getting exception on console but not able to catch
}
catch (Exception ex)//how to catch here java one throw exception
{
}
}
}
Any one suggest me correct approach to get exception in catch block.
I have a socket and I'd like to send messages and read from it.
When I read/write with the socket while the other side is offline, I get the same Exception: System.IO.IOException: Unable to read data from the transport connection: Operation on non-blocking socket would block.
How can I identify in which of the two it happened besides having two separate try-catch blocks? Can't I just get a Timeout Exception when the reading timeout is over?
example:
try
{
SendData("!GetLocation!");
string data = GetData();
}
catch (Exception ex)
{
if (ex is System.IO.IOException)
{
//How can I identify if the exception was raised at the read method or the write method?
}
}
Yeah, exception handling is heavy resource wise, but sometimes is not so bad.
If you stick to only one try-catch you can check the error message.
Note: I have also added a second try-catch for generic (non IO) errors
try
{
SendData("!GetLocation!");
string data = GetData();
}
catch (System.IO.IOException ex)
{
if (ex.Message.IndexOf("Unable to read") != -1)
{
// GetData error
}
else if (ex.Message.IndexOf("Unable to write") != -1)
{
// SendData error
}
else
{
//Other IO errors
}
}
catch(Exception exc)
{
// Unspected errors
}
you could also set a boolean variable and check its value to know where it
broke your code.
bool sendCalled = false;
try
{
SendData("!GetLocation!");
sendCalled = true;
string data = GetData();
}
catch (System.IO.IOException ex)
{
if (sendCalled)
{
// GetData error
}
else
{
// SendData error
}
}
Not that I endorse either of these solutions, but an answer is an answer: you can either
analyze the stack trace of the exception to find out which call failed (e.g. name of the method at the top of the stack frame
set a flag after the write, and do logic based on that flag
Neither of these is as straight forward as wrapping each method call. In fact, wrapping each call conveys your intent. In the catch of your first call, you can return/break/skip the read call, which explicitly tells the reader you're bailing out fast.
I'm incorporating telemetry into my product on all service requests, unfortunately that includes exceptions. A problem I'm having is I surround my requests with a try-catch and if it's successful I log the request and if there's a catch I log the exception than throw the exception so that it still gets propagated up so that it can be debugged. A problem I'm having is that with try-catch I lose all the original data from the original exception caught by my try-catch, which I think would be nice to propagate back up.
public void someFunction(object data)
{
try
{
var response = await request(data);
LogInformation(request: data, response: response);
}
catch (Exception e)
{
throw HandleAndLogException(data, e);
}
}
private HttpResponseException HandleAndLogException(object data, Exception e)
{
LogException(data: data, response: e.Message);
var resp = new HttpResponseMessage(HttpStatusCode.BadRequest) {
Content = new StringContent(e.Message)
};
return new HttpResponseException(resp);
}
So as you can see I create a new HttpResponseException and just append the message to it, but I'd rather propagate back up the exception thrown in it's entirety.
If you want to do something clever/evil, you can use the when keyword to introduce logging without breaking the stack trace on your exception.
See when contextual keyword in the C# reference on MSDN. It's supposed to be used as a filter (the method returns true or false, indicating whether that catch block should be used) but you can do whatever you want with
I think this is what you'd want, although I haven't tested it:
public void someFunction(object data)
{
try
{
var response = await request(data);
LogInformation(request: data, response: response);
}
catch (Exception e) when (HandleAndLogException(data, e))
{
throw;
}
}
private bool HandleAndLogException(object data, Exception e)
{
LogException(data: data, response: e.Message);
return true;
}
When not using a "sync handler", one needs to catch sync errors for push and pull.
PUSH:
Samples say to catch MobileServiceInvalidOperationException, MobileServicePushFailedException and Exception:
try {
await client.SyncContext.PushAsync();
}
catch (MobileServiceInvalidOperationException ex) {
// ...push failed
// ...do manual conflict resolution
}
catch (MobileServicePushFailedException ex) {
// ...push failed
// ...do manual conflict resolution
}
catch (Exception ex) {
// ...some other failure
}
PULL:
Samples say to catch MobileServiceInvalidOperationException and Exception:
try {
await syncTable.PullAsync("allitems", syncTable.CreateQuery());
}
catch (MobileServiceInvalidOperationException ex) {
// ...pull failed
}
catch (Exception ex) {
// ...some other failure
}
SYNC HANDLER:
Errors are processed in .ExecuteTableOperationAsync(). Samples say to catch
MobileServiceConflictException, MobileServicePreconditionFailedException and Exception.
FINALLY A QUESTION(S):
I hope I covered all the possible exceptions types above.
If I use a sync handler, does that mean I don't need to try-catch the push/pull/purge/etc. operations? Samples I've seen are a little confusing as they include everything (ad hoc resolution and sync handler) in the same project...
You should always place push/pull/etc. operations in a try/catch block. There is always a risk that an Exception you haven't thought of (including the network going away, for example) will happen.
I have to process items off a queue.
Deleting items off the queue is a manual call to Queue.DeleteMessage. This needs to occurs regardless of whether or not the processing succeeds.
var queueMessage = Queue.GetMessage();
try
{
pipeline.Process(queueMessage);
}
catch (Exception ex)
{
try
{
Logger.LogException(ex);
}
catch { }
}
finally
{
Queue.DeleteMessage(queueMessage);
}
Problem:
On failure, I log the error to some data store. If this logging fails (perhaps the data store is not available), I still need the message to be deleted from the queue.
I have wrapped the LogException call in another try catch. Is this the correct way or performing thing?
Following code is enough. finally blocks execute even when exception is thrown in catch block.
var queueMessage = Queue.GetMessage();
try
{
pipeline.Process(queueMessage);
}
catch (Exception ex)
{
Logger.LogException(ex);
}
finally
{
Queue.DeleteMessage(queueMessage);//Will be executed for sure*
}
The finally block always executes, even if it throws an unhandled error (unless it end the app). So yes.