通过反射,我正在调用一个可能导致异常的方法。我怎样才能将异常传递给我的调用者而没有包装反射围绕它?
我重新抛出InnerException,但这破坏了堆栈跟踪。
示例代码:
public void test1()
{
// Throw an exception for testing purposes
throw new ArgumentException("test1");
}
void test2()
{
try
{
MethodInfo mi = typeof(Program).GetMethod("test1");
mi.Invoke(this, null);
}
catch (TargetInvocationException tiex)
{
// Throw the new exception
throw tiex.InnerException;
}
}
这是在。net 6中测试的其他一些想法的一个干净、现代的实现:
public static class ExceptionExtensions
{
[DoesNotReturn]
public static void Rethrow(this Exception ex)
=> ExceptionDispatchInfo.Capture(ex).Throw();
}
我想要myObject上的PropertyName属性的值,但这将在使用反射调用方法(根据OP的问题)或其他导致您想要重新抛出内部异常的任何东西时同样有效。
try
{
object? value = myObject.GetType().GetProperty("PropertyName")?.GetValue(myObject);
}
catch (TargetInvocationException ex)
{
(ex.InnerException ?? ex).Rethrow();
}
更多的反思……
catch (TargetInvocationException tiex)
{
// Get the _remoteStackTraceString of the Exception class
FieldInfo remoteStackTraceString = typeof(Exception)
.GetField("_remoteStackTraceString",
BindingFlags.Instance | BindingFlags.NonPublic); // MS.Net
if (remoteStackTraceString == null)
remoteStackTraceString = typeof(Exception)
.GetField("remote_stack_trace",
BindingFlags.Instance | BindingFlags.NonPublic); // Mono
// Set the InnerException._remoteStackTraceString
// to the current InnerException.StackTrace
remoteStackTraceString.SetValue(tiex.InnerException,
tiex.InnerException.StackTrace + Environment.NewLine);
// Throw the new exception
throw tiex.InnerException;
}
请记住,这可能会在任何时候中断,因为私有字段不是API的一部分。参见Mono bugzilla的进一步讨论。