I am new to software development and also new to stackoverflow, so go easy on me.
BACKGROUND: I am developing a C# class library that processes xml messages sent by a third party application over tcp/ip (using Async sockets). I am using com-interop in order to expose the class library to a Vb6 application. When the C# library processes the xml it receives over the socket, it raises various events that the consuming vb6 application subscribes to (this way, when we eventually rewrite the entire application in .Net we will already be done with this component).
QUESTION: I want to catch all unhandled exceptions for LOGGING PURPOSES ONLY. In a winforms application you can hook up an event to the AppDomain.CurrentDomain.UnhandledException and to Application.ThreadException. Is there no way to similarly grab exception data to log the information in a class library?
Important Points:
I am not trying to recover from these exceptions, but just log them and let the exception propogate up and crash the app if need be.
I am doing my best to catch all specific exceptions locally wherever I know that they might occur. Therefore my purpose is to just log the truly unexpected exceptions.
- I know that some will say that this would be a bad design pattern. I should instead let the caller deal with these exceptions. The problem is the vb6 application does not have as robust error handling in place as I would like. Primarily, I want to log the stack trace so that if the vb6 app crashes due to my dll, I can view the log in order to be alerted to potential areas of my c# code that might need to be changed.
Can anyone provide me with some direction? The best option that I have found so far seems to put a generic try catch block in every public method, log the exception, and then throw it. This seems less than ideal:
public void SomeMethod()
{
try
{
// try something here...
}
catch (Exception ex)
{
Log(ex);
throw;
}
}
Not only does this seem like a poor design, but additionally I do not know what would happen if one of the async callbacks causes an exception on a different thread than the method was called on. Would this general try/catch block still catch such an exception?
Thanks for any assistance.
EDIT: I originally marked @Eric J.'s answer as correct, but after trying to implement the solution I have found that it won't work well with the async callbacks from the socket class that I am using. Once a threadpool thread is used to fire the async callback, I cannot seem to catch any exceptions that occur any later in the stack. Will I need to use an AOP framework, or is there any other way to catch these exceptions?