Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving stack trace when rethrowing exceptions in Silverlight

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?

like image 255
Stephen McDaniel Avatar asked Nov 29 '10 23:11

Stephen McDaniel


People also ask

How do you preserve stack trace?

To keep the original stack trace information with the exception, use the throw statement without specifying the exception.

What does end of stack trace from previous location where exception was thrown mean?

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.


1 Answers

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.

like image 58
Guffa Avatar answered Nov 15 '22 07:11

Guffa