c# – 从代理返回异常

我正在使用大量未记录的Castle动态代理系统.我设法让它做我想要的几乎所有事情,除了一件事:你如何使代理方法抛出异常而不是返回值?

public sealed class MyInterceptor : IInterceptor
{
  public void Intercept(IInvocation invocation)
  {
    if (CheckArgs(invocation.Arguments))
    {
      invocation.ReturnValue = DoRealWork(invocation.Arguments);
    }
    else
    {
      invocation.Exception = new InvalidOperationException(); // How?
    }
  }
}

解决方法

从代理对象的角度来看,拦截器是不可见的;它只是调用自己的虚方法,DynamicProxy在将ReturnValue返回给调用者之前调用正确的拦截方法.

因此,如果你想抛出异常只是从拦截器抛出它:

if (CheckArgs(invocation.Arguments))
{
  invocation.ReturnValue = DoRealWork(invocation.Arguments);
}
else
{
  throw new InvalidOperationException();
}

调用者的角度来看,它将是被调用方法中的一个例外.

编辑评论

关于生成器中抛出的异常的类型,我有正确的类型,而不是包装器:

public interface IDummy
{
    string DoSomething();
}

public class Dummy: IDummy {
    public virtual string DoSomething()
    {
        return string.Empty;
    }
}

public class MyCustomException : Exception {}

public class CustomIntercept: IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        throw new MyCustomException();
    }
}

internal class Program
{
    private static void Main(string[] args)
    {
        var pg = new proxygenerator();
        GetValue(pg.CreateInterfaceProxyWithoutTarget<IDummy>(new CustomIntercept()));
        GetValue(pg.CreateClassproxy<Dummy>(new CustomIntercept()));
        GetValue(pg.CreateClassproxyWithTarget<Dummy>(new Dummy(),new CustomIntercept()));
        GetValue(pg.CreateInterfaceProxyWithTarget<IDummy>(new Dummy(),new CustomIntercept()));
    }

    private static void GetValue(IDummy dummy)
    {
        try
        {
            dummy.DoSomething();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.GetType().Name);
        }
    }
}

所有四个输出都是MyCustomException

你能确保TargetInvocationException不是来自你自己的代码吗?您正在使用什么版本的DynamicProxy(我正在使用Castle.Core 3.2中的那个版本)

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...