网站建设 淘宝描述psd,图片设计制作哪个软件好手机,安康做网站哪家好,百度推广开户多少钱咨询区 skolima我用反射来尝试调用一个可能会引发异常的方法#xff0c;我如何将这个异常信息传递给调用者#xff0c;而不需要通过反射包装器包装它。我目前的是再 throw 一次异常#xff0c;但这种做法会销毁第一次异常的栈信息#xff0c;参考如下代码#xff1a;publi… 咨询区 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 ActionException _preserveInternalException;static ExceptionHelper(){MethodInfo preserveStackTrace typeof( Exception ).GetMethod( InternalPreserveStackTrace, BindingFlags.Instance | BindingFlags.NonPublic );_preserveInternalException (ActionException)Delegate.CreateDelegate( typeof( ActionException ), 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
}点评区 在实际开发中这确实是一个刚性需求没想到有这么多种解法学习了。