2010-11-29 88 views
5

我需要重新抛出被捕获并存储在其他地方的异常没有丢失有关何时第一次捕获/存储异常的堆栈跟踪信息。我的代码看起来是这样的:在Silverlight中重新抛出异常时保留堆栈跟踪

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中工作的堆栈跟踪?

回答

3

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

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

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

+0

这看起来像我现在唯一的选择。不幸的是,这可能会干扰现有的代码,比如“catch(SpecificExceptionClass)”,否则它会检查异常类型。理想情况下,我希望尽可能避免包装Exception,因为我不希望消费者必须开始检查InnerExceptions是否存在“真实”异常。 – 2010-11-29 23:26:05

3

您可以使用

catch(Exeption) 
{ 
    throw; 
} 

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

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

因为你的情况,你会抛出参数error而不是e

+0

如果你想提及在这里不起作用的每一种可能的解决方案,你忘了最简单的解决方案:根本就没有发现异常。 ;) – Guffa 2010-11-29 23:24:35

相关问题