Sync conflict handling in Azure Mobile Services: ad hoc vs sync handler - c#

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.

Related

possible exceptions from IClientProxy.SendAsync (from Microsoft.AspNetCore.SignalR)

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

Send exception to Caller method in c#

Hello guys i'm working on Database assignment in this i have one windows form and one class that i use to connect database and to execute queries and non-queries.
Question: I m using Post-Message label which inform only when "Product added successfully".but when i send wrong-data which can occur exception in executeNonQuery() in database class and after catching this exception and showing Error in message box.Control goes back to caller and it prints lblPostMsg in both cases which is "Product has been added successfully".
I want that when exception occur in database class i can stop executing rest of the code or if there is way that exception in calling method can be caught by caller method.
below is Code of windows Form button
private void btnInsert_Click(object sender, EventArgs e)
{
con = new DbConnection();
con.SqlQuery("INSERT INTO products VALUES(#products_ID,#products_Name)");
con.cmd.Parameters.AddWithValue("#products_ID", txtProID.Text);
con.cmd.Parameters.AddWithValue("#products_Name", txtProName.Text);
try
{
con.ExecuteNonQueryF();
this.categoriesTableAdapter1.Fill(this.purchasemasterDS.categories);
SystemSounds.Beep.Play();
lblPostMsg.Show();
lblPostMsg.Text = "Product has been added successfully";
}
catch (Exception ex)
{
throw;
}
finally
{
con.CloseCon();
}
}
This code is from dbclass
public void ExecuteNonQueryF()
{
try
{
_con.Open();
cmd.ExecuteNonQuery();
}
catch (System.Exception ex)
{
MessageBox.Show("Exception " + ex);
}
you are catching, handling, and suppressing the Exception in ExecuteNonQueryF:
catch (System.Exception ex)
{
MessageBox.Show("Exception " + ex);
}
Though this handles the Exception by showing the message, it causes the code to continue executing; the Exception won't be raised to the caller.
If you add throw after your MessageBox.Show is executed, the Exception will be raised to the caller and execution stops.
catch (System.Exception ex)
{
MessageBox.Show("Exception " + ex);
throw;
}
Another option is to completely remove that try-catch in ExecuteNonQueryF - letting the caller (your button onclick method) handle the Exception.
you need to throw an explicit exception in ExecuteNonQuery's catch block like
throw new Exception(ex)
and then in calle's catch block you need to write "return" to return from function. This will stop furter execution of function.
If you want the Exception will be raised to the caller and execution stops, then you must use throw at the last line of your catch block.
catch (System.Exception ex)
{
/*
write your desire code. then throw
*/
throw;
}

DirectoryNotFoundException was unhandled by user code

I'm quite new to the try catch and exception handling. I want my program to catch the exception when the directory or file is not found.
Whenever I run the program I get the error "DirectoryNotFoundException was unhandled by user code - An exception of type 'System.IO.DirectoryNotFoundException' occured in something.dll but was not handled in user code"
I can see that Visual Studio breaks at the DirectoryNotFoundDirection, any ideas?
try {
LiveDownloadOperation operation = await connectClient.CreateBackgroundDownloadAsync(filePath);
var result = await operation.StartAsync();
}
catch (FileNotFoundException filEx) {
Debug.WriteLine(filEx.Message);
throw filEx;
}
catch (DirectoryNotFoundException dirEx) {
Debug.WriteLine(dirEx.Message);
throw;
}
catch (IOException ioEx) {
Debug.WriteLine(ioEx.Message);
throw ioEx;
}
catch (Exception ex) {
Debug.WriteLine(ex.Message);
throw;
}
EDIT: to show code inside try
Because the directory does not exist (or has permissions problems, etc.), it throws an DirectoryNotFoundException.
Which you handle, then reraise -- because of the, the debugger rightly says that the exception is not handled.

Try inside catch to ensure finally executes

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.

Handling Error "WebDev.WebServer.Exe has stopped working"

Is there a way to handle the error "WebDev.WebServer.Exe has stopped working" in ASP.NET and keep the page running or even the just the WebServer running? Or is this an impossible task and is essentially like asking how to save someone's life after they've died?
I have the error-causing code inside a try/catch block, but that doesn't make a difference. I've also tried registering a new UnhandledExceptionEventHandler, but that didn't work either. My code is below in case I'm doing something wrong.
Also to be clear, I'm not asking for help on how to prevent the error; I want to know if and when the error happens if there's anything I can do to handle it.
UPDATE 1: TestOcx is a VB6 OCX that passes a reference of a string to a DLL written in Clarion.
UPDATE 2: As per #JDennis's answer, I should clarify that the catch(Exception ex) block is not being entered either. If I removed the call to the OCX from the try\catch block it still won't reach the UnhandledException method. There are essentially two areas that don't ever get executed.
UPDATE 3: From #AndrewLewis, I tried to also add a regular catch block to catch any non-CLS compliant exceptions, and this did not work either. However, I later found that since .NET 2.0 on, all non-CLS exceptions are wrapped inside RuntimeWrappedException so a catch (Exception) will catch non-CLS compliant exceptions too. Check out this other question here for more info.
public bool TestMethod()
{
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
string input = "test";
string result = "";
try
{
TestOcx myCom = new TestOcx();
result = myCom.PassString(ref input); // <== MAJOR ERROR!
// do stuff with result...
return true;
}
catch (Exception ex)
{
log.Add("Exception: " + ex.Message); // THIS NEVER GETS CALLED
return false;
}
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
// THIS NEVER GETS CALLED
try
{
Exception ex = (Exception)e.ExceptionObject;
log.Add("Exception: " + ex.Message);
}
catch (Exception exc)
{
log.Add("Fatal Non-UI Error: " + exc.Message);
}
}
You should try catching non-CLS compliant exceptions to make sure nothing is being thrown (keep in mind you don't want to do this in production, always be specific!):
try
{
TestOcx myCom = new TestOcx();
result = myCom.PassString(ref input); // <== MAJOR ERROR!
// do stuff with result...
return true;
}
catch (Exception ex)
{
log.Add("Exception: " + ex.Message); // THIS NEVER GETS CALLED
return false;
}
catch
{
//do something here
}
Your code reads //THIS NEVER GETS CALLED.
If you catch the exception it is no longer un-handled. this is why it doesn't fire an unhandledexception event.

Categories