I need to rethrow an Exception that was caught and stored elsewhere without losing the stack trace information about when the Exception was first caught/stored. My code looks something like this:
public void Test()
{
int someParameter = 12;
ExecuteSomeAsyncMethod(someParameter, CallbackMethod);
}
public void CallbackMethod(object result, Exception error)
{
//Check for exceptions that were previously caught and passed to us
if(error != null)
//Throwing like this will lose the stack trace already in Exception
//We'd like to be able to rethrow it without overwriting the stack trace
throw error;
//Success case: Process 'result'...etc...
}
I've seen solutions to this problem that use reflection (for example here and here) or use Serialization (for example here) but none of those will work for me in Silverlight (private reflection is not allowed and the classes/methods used in the serialization approach don't exist in Silverlight).
Is there any way to preserve the stack trace that works in Silverlight?
To keep the original stack trace information with the exception, use the throw statement without specifying the exception.
When the exception is restored, the following string is inserted in the stack trace to indicate the restore point: "End of stack trace from the previous location where the exception was thrown". This is similar to the way inner exceptions or marshaled exceptions are indicated in stack traces.
Throw a new exception with the exception as inner exception:
throw new ApplcationException("Error message", error);
The inner exception will keep it's stack trace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With