Reputation: 16733
I have create a console application that logs messages successfully when I log directly from Main()
. What I would like to do is setup a handler to handle all unhandled exceptions:
class Program
{
private static Logger logger = LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
throw new ApplicationException("Throwing an unhandled exception!"); //This line keeps getting hit
Console.ReadLine();
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var exc = (Exception)e.ExceptionObject;
logger.ErrorException("Another exception occured!", exc);
}
}
This application never unloads, and I'm trying to figure out why. It throws my ApplicationException
, and CurrentDomain_UnhandledException()
is then executed, but then the debugger returns to the line: throw new ApplicationException()
. CurrentDomain_UnhandledException()
is executed again, and then I'm looped back to the line throwing the exception into infinity and beyond.
And even though logger.ErrorException()
is called, nothing is written to the database.
Upvotes: 0
Views: 237
Reputation: 29668
For the first part, what happens outside of debugging when you run it normally?
I suspect because you're debugging when it's raised the debugger unwinds the callstack, thus you end up back in the same place where the exception was thrown, so continually bashing continue doesn't get you anywhere.
I beleive there's an option to prevent this behaviour, see Tools >> Options >> Debugging >> General
.
However I would leave it on and accept this as intended behaviour (as long as unhandled exceptions are correctly handled outside of debugging).
As for the second part, on that i'm unsure it could be that whatever appender you're using simply doesn't get chance to flush. I'd switch to file and see if it logs there to check this.
Upvotes: 1