咨询区
skolima
我用反射来尝试调用一个可能会引发异常的方法,我如何将这个异常信息传递给调用者,而不需要通过反射包装器包装它。
我目前的是再 throw 一次异常,但这种做法会销毁第一次异常的栈信息,参考如下代码:
public void test1()
{// Throw an exception for testing purposesthrow new ArgumentException("test1");
}void test2()
{try{MethodInfo mi = typeof(Program).GetMethod("test1");mi.Invoke(this, null);}catch (TargetInvocationException tiex){// Throw the new exceptionthrow tiex.InnerException;}
}
回答区
Paul Turner
在 .NET 4.5 中有一个 ExceptionDispatchInfo
类,它会帮你捕获异常信息并且在重新 throw 时不会改变调用栈,参考如下代码:
using ExceptionDispatchInfo = System.Runtime.ExceptionServices.ExceptionDispatchInfo;try
{task.Wait();
}
catch(AggregateException ex)
{ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
它可以应用到任何异常上,包括案例上的 AggregateException。
Eric
我写了一个扩展方法,你可以将抛出的 exception 丢到扩展方法中即可,这个 exception 原始的栈就会被保留。
public static class ExceptionHelper
{private static Action<Exception> _preserveInternalException;static ExceptionHelper(){MethodInfo preserveStackTrace = typeof( Exception ).GetMethod( "InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic );_preserveInternalException = (Action<Exception>)Delegate.CreateDelegate( typeof( Action<Exception> ), preserveStackTrace ); }public static void PreserveStackTrace( this Exception ex ){_preserveInternalException( ex );}
}
Anton Tykhyy
你应该在重新抛出异常之前要尽可能的保留栈信息,参考如下代码:
static void PreserveStackTrace (Exception e)
{var ctx = new StreamingContext (StreamingContextStates.CrossAppDomain) ;var mgr = new ObjectManager (null, ctx) ;var si = new SerializationInfo (e.GetType (), new FormatterConverter ()) ;e.GetObjectData (si, ctx) ;mgr.RegisterObject (e, 1, si) ; // prepare for SetObjectDatamgr.DoFixups () ; // ObjectManager calls SetObjectData// voila, e is unmodified save for _remoteStackTraceString
}
点评区
在实际开发中这确实是一个刚性需求,没想到有这么多种解法,学习了。