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

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.

Related

Why I am not getting exception trace in error redirect page?

In my quest to implement best custom error handling practices, I came up with an idea to not use try catch any where in my code. Instead, I have decided to use customErrors mode="On" and redirect to error page and show exception detail in this page.
//My test code from which error will come
public ActionResult Index()
{
AAA aa = null;
aa.a = "a";
}
//My web.config file
<customErrors mode="On" defaultRedirect="~/Errors/Error.aspx">
<error statusCode="404" redirect="~/Errors/404.html" />
</customErrors>
//My error handling page(Error.aspx):
protected void Page_Load(object sender, EventArgs e)
{
Exception error;
error = Server.GetLastError();
}
I believe I should get error message in error in my error handling page. But I always get null.
How do I get the exception message in error handling page?
Let me shed some light in how I generally handle exceptions in the projects I work on. But let's break down into sections.
Error pages
The error pages should not show the real exception when on Production. The user has no need to know that the DB had a failure, which could expose your system to security issues. A page with a generic error or a well documented error code would do the job.
But, of course, on your dev environment it's ok to show exceptions. I'd suggest to use customErrors mode="RemoteOnly" in this case.
Error code
Depending on the system you are developing it would be important to have an error code with the message. For example, the user could see "Unable to connect (XYZ_1234)" or "Unable to connect (ABC_9876)" - same message, different codes - and send it to the support team. If the support team has a document matching the codes with the real exceptions they will be able to send a proper report to the devs.
Try/Catch blocks
Try/Catch is your best friend when it comes to exception. Especially because it will help you to customize the exception if necessary. You could have a series of custom exception classes - each with its own characteristic - that would help you to know the problem even before debugging. One simple example:
public class ExceptionWithCode : Exception
{
public ExceptionWithCode(string code, string message) : base(message)
{
this.Code = code;
}
public string Code { get; }
}
In the code you should approach it in more or less this way:
try
{
// Do whatever database operation here
}
catch (SqlException ex)
{
// Log the exception
_logService.Log(ex);
// Throw something else to the user
throw new ExceptionWithCode("XYZ_1234", "Unable to connect");
}
catch (Exception ex)
{
// Log the exception
_logService.Log(ex);
// Throw something else to the user
throw new ExceptionWithCode("ABC_9876", "Unable to connect");
}
Notice that I am using 2 catches. The first is because I know this exception may happen, since I am connecting to the DB, the second is in case any other thing may happen. Besides, the user doesn't know the real exception as he/she is getting just a random exception with code instead of a db connection failure.
Logs
That's a very important part. Remember: You should never show the real exceptions to the user. Instead, log them in a place where you can easily access. That could be in a file in the server, the database or even in the Windows Event Logs. You don't necessarily need to write your own logging tool, you can use anything available on the internet. My favorite is SeriLog, since I log most of my events/exceptions in text files. But I've used ELMAH for quite some time with .NET Framework and it was pretty good for XML formatted logs.
That works for me because:
User is informed of the problem and can communicate with the support
I am not tipping off any intruders regarding the flaws of my system (at least not clearly)
I know what kind of exception the user saw thanks to the error code he gave me
There are logs to be analyzed whenever I need

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.

Azure Service Fabric FabricObjectClosedException

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.

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.

ExecutionEngineException not caught

I am curious why ExecutionEngineException is not caught when I am executing the code below.
try
{
((Window)window).Close();
}
catch (Exception e)
{
Console.WriteLine(e);
}
The WriteLine will never be reached. Any ideas how to catch this exception ?
Note: I know the exception is thrown by AvalonDock when one of DockablePanes is in AutoHide mode, is visible and user is trying to close wpf window.
Update:
I've read the remarks section on msdn regarding this exception:
The CLR never throws this exception in such a way that managed code can catch it.
So the question is how to close application nicely after something like that.
The ExecutionEngineException represents a fatal error from which you should not try to recover or handle. You need to tackle this at the source of the problem before it happens and not try to handle it gracefully.
Since you say you already know the source of the problem you should take actions to prevent the application to reach the state where its forced to throw the fatal exception.
Consider adding [System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions()] attribute to the method that your code is executed.

Categories