加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 从代理返回异常

发布时间:2020-12-15 22:11:10 所属栏目:百科 来源:网络整理
导读:我正在使用大量未记录的Castle动态代理系统.我设法让它做我想要的几乎所有事情,除了一件事:你如何使代理方法抛出异常而不是返回值? public sealed class MyInterceptor : IInterceptor{ public void Intercept(IInvocation invocation) { if (CheckArgs(in
我正在使用大量未记录的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中的那个版本)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读