Azure Service Fabric FabricObjectClosedException - c#

I have a stateful service that stores things in a IReliableDictionary. After deployed to local cluster, I restarted the primary node to test the failover, however, after I do that, the code StateManager.GetOrAddAsync>("MyDictionary") throws FabricNotPrimaryException, then in later trials it throws FabricObjectClosedException. What are some of the things that I can check to troubleshoot this?

The basic way to troubleshoot errors like this is to catch and log the exception being thrown:
try
{
using (var tx = StateManager.CreateTransaction())
{
await dictionary.AddOrUpdateAsync(tx, dto.Id, dto, (key, _) => dto);
await transaction.CommitAsync();
}
}
catch (FabricObjectClosedException ex)
{
ServiceEventSource.Current.Message(ex.ToString());
throw; // Pass the exception up as we only log it here.
}
However, your problem might be a very simple typo like a missing [DataContractAttribute] on a DTO class. In that case it might be easier to simply debug the problem to quickly understand and fix the problem. To do that you should add the System.Fabric.FabricObjectClosedException to Visual Studio and then enable "break when thrown" in the debugger:
Show the Exception Settings window (Debug > Windows > Exception Settings)
Select the Common Language Runtime Exceptions category in the list of exception categories
Click the green + (plus) button to add a new exception type
Type System.Fabric.FabricObjectClosedException in the text box and hit enter
When a new exception type is added the Break When Thrown check box is already checked.
Next time you execute your application in the debugger the debugger will break when a FabricObjectClosedException is thrown and you should be able to understand what went wrong.

Related

C# How to investigate: An unhandled exception was thrown by the application

Hi I am getting the following error in my asp.net core logs:
Microsoft.AspNetCore.Server.Kestrel|Connection id "XXXXX", Request id "YYYY:0000": An unhandled exception was thrown by the application.
Struggling to see how to investigate this further - how can I track down what is causing this? Is there any additional logging I can enable?
You will need to decorate your code with try/catch:
try
{
//code logic goes here
}
catch(Exception ex)
{
//handle exception here
//ex.Message - this will give you string description of the exception
//ex.InnerException - this will provide you more details when you debug
//and have a break point in the exception section then you can view
//more details on the exception
}
I hope this helps.
You can't catch this exception it is just logged. See for example source code. In vs you can set a functional breakpoint and load the symbols where needed. Then you can set more breakpoints where needed.
You can try using the ILogger from the Microsoft.Extensions.Logging, using the Method LogError.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loggerextensions.logerror?view=dotnet-plat-ext-7.0
You will need to set the Log to output where you prefer, in the link bellow you can see the basic settings.
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-7.0
In addition, if possible to debug, you can just enable more Exception setting while debugging.
At the bottom of the Visual Studio, this tab will appear, just enabled more options until a more specific exception appears.

C# crashes despite try/catch block [duplicate]

I would like Visual Studio to break when a handled exception happens (i.e. I don't just want to see a "First chance" message, I want to debug the actual exception).
e.g. I want the debugger to break at the exception:
try
{
System.IO.File.Delete(someFilename);
}
catch (Exception)
{
//we really don't care at runtime if the file couldn't be deleted
}
I came across these notes for Visual Studio.NET:
1) In VS.NET go to the Debug Menu >>
"Exceptions..." >> "Common Language
Runtime Exceptions" >> "System" and
select "System.NullReferenceException"
2) In the bottom of that dialog there
is a "When the exception is thrown:"
group box, select "Break into the
debugger"
3) Run your scenario. When the
exception is thrown, the debugger will
stop and notify you with a dialog that
says something like:
"An exception of type "System.NullReferenceException" has
been thrown.
[Break] [Continue]"
Hit [Break]. This will put you on the
line of code that's causing the
problem.
But they do not apply to Visual Studio 2005 (there is no Exceptions option on the Debug menu).
Does anyone know where the find this options dialog in Visual Studio that the "When the exception is thrown" group box, with the option to "Break into the debugger"?
Update: The problem was that my Debug menu didn't have an Exceptions item. I customized the menu to manually add it.
With a solution open, go to the Debug - Windows - Exception Settings (Ctrl+Alt+E) menu option. From there you can choose to break on Thrown or User-unhandled exceptions.
EDIT: My instance is set up with the C# "profile" perhaps it isn't there for other profiles?
There is an 'exceptions' window in VS2005 ... try Ctrl+Alt+E when debugging and click on the 'Thrown' checkbox for the exception you want to stop on.
Took me a while to find the new place for expection settings, therefore a new answer.
Since Visual Studio 2015 you control which Exceptions to stop on in the Exception Settings Window (Debug->Windows->Exception Settings). The shortcut is still Ctrl-Alt-E.
The simplest way to handle custom exceptions is selecting "all exceptions not in this list".
Here is a screenshot from the english version:
Here is a screenshot from the german version:
From Visual Studio 2015 and onward, you need to go to the "Exception Settings" dialog (Ctrl+Alt+E) and check off the "Common Language Runtime Exceptions" (or a specific one you want i.e. ArgumentNullException) to make it break on handled exceptions.
Step 1
Step 2
Check Managing Exceptions with the Debugger page, it explains how to set this up.
Essentially, here are the steps (during debugging):
On the Debug menu, click Exceptions.
In the Exceptions dialog box, select Thrown for an entire category of exceptions, for example, Common Language Runtime Exceptions.
-or-
Expand the node for a category of exceptions, for example, Common Language Runtime Exceptions, and select Thrown for a specific exception within that category.
A technique I use is something like the following. Define a global variable that you can use for one or multiple try catch blocks depending on what you're trying to debug and use the following structure:
if(!GlobalTestingBool)
{
try
{
SomeErrorProneMethod();
}
catch (...)
{
// ... Error handling ...
}
}
else
{
SomeErrorProneMethod();
}
I find this gives me a bit more flexibility in terms of testing because there are still some exceptions I don't want the IDE to break on.
The online documentation seems a little unclear, so I just performed a little test. Choosing to break on Thrown from the Exceptions dialog box causes the program execution to break on any exception, handled or unhandled. If you want to break on handled exceptions only, it seems your only recourse is to go through your code and put breakpoints on all your handled exceptions. This seems a little excessive, so it might be better to add a debug statement whenever you handle an exception. Then when you see that output, you can set a breakpoint at that line in the code.
There are some other aspects to this that need to be unpacked. Generally, an app should not throw exceptions unless something exceptional happens.
Microsoft's documentation says:
For conditions that are likely to occur but might trigger an exception, consider handling them in a way that will avoid the exception.
and
A class can provide methods or properties that enable you to avoid making a call that would trigger an exception.
Exceptions degrade performance and disrupt the debugging experience because you should be able to break on all exceptions in any running code.
If you find that your debugging experience is poor because the debugger constantly breaks on pointless exceptions, you may need to detect handled exceptions in your tests. This technique allows you to fail tests when code throws unexpected exceptions.
Here are some helper functions for doing that
public class HandledExceptionGuard
{
public static void DoesntThrowException(Action test,
Func<object?, Exception, bool>? ignoreException = null)
{
var errors = new List<ExceptionInformation>();
EventHandler<FirstChanceExceptionEventArgs> handler = (s, e) =>
{
if (e.Exception is AssertFailedException) return;
if (ignoreException?.Invoke(s, e.Exception) ?? false) return;
errors.Add(new ExceptionInformation(s, e.Exception, AppDomain.CurrentDomain.FriendlyName));
};
AppDomain.CurrentDomain.FirstChanceException += handler;
test();
AppDomain.CurrentDomain.FirstChanceException -= handler;
if (errors.Count > 0)
{
throw new ExceptionAssertionException(errors);
}
}
public async static Task DoesntThrowExceptionAsync(Func<Task> test,
Func<object?, Exception, bool>? ignoreException = null)
{
var errors = new List<ExceptionInformation>();
EventHandler<FirstChanceExceptionEventArgs> handler = (s, e) =>
{
if (e.Exception is AssertFailedException) return;
if (ignoreException?.Invoke(s, e.Exception) ?? false) return;
errors.Add(new ExceptionInformation(s, e.Exception, AppDomain.CurrentDomain.FriendlyName));
};
AppDomain.CurrentDomain.FirstChanceException += handler;
await test();
AppDomain.CurrentDomain.FirstChanceException -= handler;
if (errors.Count > 0)
{
throw new ExceptionAssertionException(errors);
}
}
}
If you wrap any code in these methods as below, the test will fail when a handled exception occurs. You can ignore exceptions with the callback. This validates your code against unwanted handled exceptions.
[TestClass]
public class HandledExceptionTests
{
private static void SyncMethod()
{
try
{
throw new Exception();
}
catch (Exception)
{
}
}
private static async Task AsyncMethod()
{
try
{
await Task.Run(() => throw new Exception());
}
catch (Exception)
{
}
}
[TestMethod]
public void SynchronousTest()
{
HandledExceptionGuard.DoesntThrowException(() => SyncMethod());
}
[TestMethod]
public async Task AsyncTest()
{
await HandledExceptionGuard.DoesntThrowExceptionAsync(() => AsyncMethod());
}
}

Visual Studio - suppress certain "Exception thrown" messages

Can you hide "Exception thrown" messages in output for certain methods (certain code areas)?
I use HttpWebRequest for server communication. I periodically check if the server is available (a few times every second). When a server is not reachable HttpWebRequest throws an exception. I catch it and set GUI elements enabled to false. The problem is when the server is unreachable, output window gets cluttered up with "Exception thrown" messages.
I know you can right-click output window and uncheck "Exception Messages". But I am not only one working on the project and there might be someone who wants to see some other exception messages (in their part of the project).
Example of what I need:
// Keep showing "Exception thrown" message in this method.
static void Foo()
{
try
{
throw new NotImplementedException();
}
catch (NotImplementedException ex)
{
// Process exception
}
}
// Suppress "Exception thrown" message when it is thown in this method.
static void FooSuppress()
{
try
{
throw new ArgumentException();
}
catch (ArgumentException ex)
{
// Process exception
}
}
static void Main(string[] args)
{
Foo();
FooSuppress();
}
Current output:
Exception thrown: 'System.NotImplementedException' in ExceptionTest.dll
Exception thrown: 'System.ArgumentException' in ExceptionTest.dll
Desired output:
Exception thrown: 'System.NotImplementedException' in ExceptionTest.dll
Edit:
Enabling Just my code in Tools/Options/Debugging might help.
We used Npgsql to access PostgreSQL database and some calls had timeout. Everytime call timeouted "Exception thrown" was written to output window (and there were a lot). Just my code prevents that.
To disable the Exception messages:
(1)Like your previous reply, you could disable it in the Output windows.
(2)You could also disable it under TOOLS->Options->Debugging->Output Window.
(3)Or you could just throw the Exception using the Exception Settings under Debug menu->Windows->Exception Settings.
I don't find other workaround to disable it unless you really resolve/handle the Exceptions in your code. I test it using the VS2015 version.
No other good suggestion, but I help you submit a feature here: https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/16752127-visual-studio-suppress-certain-exception-thrown-me
You could vote it.
If you are willing to wait a little bit or use a pre-release version, the next version of Visual Studio (VS 15) will have a feature "Add Conditions to Exception Settings"
Add Conditions to Exception Settings When you configure the
debugger to break on thrown exceptions, you can add conditions so that
the debugger will only break when exceptions are thrown in specified
modules.
This will allow you to set filters on when exceptions should break.

Application does not exit after Exception is thrown

I have unusual (for me) problem with thrown exception. After exception is thrown application loops on it and doesn't exit.
if(!foundRemoteID)
{
throw new ArgumentOutOfRangeException(
"value",
"Remote ID was not found."
);
}
I have inserted brakepoint on "if(!foundRemoteID)" line but the program doesn't hit it at all after firs thrown exception. It just loops over and over on "throw new (..).
-I do not have try{} catch{} blocks at all at any level.
-There is no loop that contains this code
I have even tried putting it into:
try
{
(..)
}
finally
{
Enviroment.Exit(1);
}
but finally{} block is never hit.
Other throw new (..) in this class is acting same way.
Am I missing something trivial?
UPDATE:
Problem is not related to my project. I have just created a simple console application that has only
throw new FileNotFoundException();
In Main() method and problem persists.
I have already tried resetting VS2010 settings to default and it didn't help.
Most likely this is not the actual behavior of your application - rather, Visual Studio is set to always break when there is an unhandled ArgumentOutOfRangeException.
You can verify this by pressing "Start without debugging".
If you want to change the settings, browse to the menu to Debug -> Exceptions and you should see the following. Then uncheck "User-unhandled."
Personally, I recommend leaving the setting the way it is in most cases. It really helps when hunting down unhandled exceptions.

Exception handling c# doesn't behave as I expect -- why?

I have the following C# code:
try
{
response = this.writeDataToChannel(writeRequest);
if (response.Failures != null)
{
Console.WriteLine(response.Failures.First().cause);
}
}
catch (TimeoutException te)
{
Console.Error.WriteLine(te.Message);
}
When I run this code in release and push a lot of data to the service, VS2010 stops on the "writeDataToChannel" line with a TimeoutException. Shouldn't my catch block catch the exception and just print it when the timeout happens?
The "writeDataToChannel" code was generated from a WSDL, the writes always work until I push tons of data to the webservice, so I don't think there is a problem with my request.
It is not a namespace issue, in both cases it is a System.TimeoutException.
It sounds to me like you have Visual Studio set to stop on a thrown exception. Go to the menu item Debug->Exceptions and see what your CLR Exceptions settings are. To get the behavior that you're describing, you don't want to stop on caught or uncaught exceptions.
Alternatively, don't run it under the debugger.
You probably need to tell VS to not break on each thrown exception in the exceptions dialog (ctrl + alt + e and uncheck CLR exceptions)
As others have mentioned, this happens when you are debugging the project (by hitting F5, or clicking the green triangle button ">").
To run without debugging, type CTRL + F5, or click the "Start without debugging" menu choice or button.
You don't necessarily need to remove the option to stop on exceptions like others have mentioned, but go ahead and do so if it becomes annoying.
You will need to throw in order to catch something in your try/catch
throw

Categories