在Silverlight中重新抛出异常时保留堆栈跟踪

时间:2010-11-29 23:10:47

标签: c# .net silverlight exception

我需要重新抛出一个被捕获并存储在其他位置的异常,而不会丢失有关何时首次捕获/存储异常的堆栈跟踪信息。我的代码看起来像这样:

    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...
    }

我见过这个问题的解决方案,使用反射(例如herehere)或使用序列化(例如here),但这些都不适用于我Silverlight(不允许私有反射,Silverlight中不存在序列化方法中使用的类/方法)。

有没有办法保留在Silverlight中有效的堆栈跟踪?

2 个答案:

答案 0 :(得分:3)

抛出一个新异常,异常为内部异常:

throw new ApplcationException("Error message", error);

内部异常将保持它的堆栈跟踪。

答案 1 :(得分:3)

您可以使用

catch(Exeption)
{
   throw;
}

catch(Exception e)
{
   throw new Exception(e);
}

两者都将保持堆栈跟踪。第一个解决方案在您的示例中似乎不可能,但第二个解决方案应该可行。

在你的情况下,你会抛出参数error而不是e