Re-throwing exceptions without losing the original stack strace in .NET

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:
01 throwThings are a bit different outside a catch block, though. Consider the following code sample:
02_throw_messagehandler_wrong.png

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:
03_throw_messagehandler_right

That’s it! Happy coding 🙂

Advertisements