This is nothing new – if you need to re-throw an exception in a catch block without losing the stack trace you use the throw statement like this:
Things are a bit different outside a catch block, though. Consider the following code sample:
Just to give you some context, this excerpt is from a MessageHandler that I implemented to log HTTP requests and responses in a ASP.NET Web API application (based on Log message Request and Response in ASP.NET WebAPI). I have an ExceptionHandler class that will log all unhandled exceptions, that’s why I’m re-throwing the exception here.
The problem is that the following command will instantiate a new exception and clear the original stack trace:
throw exception;
Fortunately there is an easy fix. From .NET v4.5 you can use ExceptionDispatchInfo class to capture the current state of an exception and re-throw an exception without changing the original stack-trace:
That’s it! Happy coding š