【问题标题】:Using Unity 2.0 handle exception使用 Unity 2.0 处理异常
【发布时间】:2011-04-13 02:34:27
【问题描述】:

当我使用 Unity 2.0 处理异常时,我遇到了一些问题,如下所示:

public class TraceBehavior : IInterceptionBehavior
{
    public IEnumerable<Type> GetRequiredInterfaces()
    {
        return Type.EmptyTypes;
    }

    public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
    {
        Console.WriteLine(string.Format("Invoke method:{0}",input.MethodBase.ToString()));
        IMethodReturn result = getNext()(input, getNext);
        if (result.Exception == null)
        {
            Console.WriteLine("Invoke successful!");
        }
        else 
        {
            Console.WriteLine(string.Format("Invoke faild, error: {0}", result.Exception.Message));
            result.Exception = null;
        }
        return result;
    }

    public bool WillExecute { get { return true; } }
}

我已经设置了result.Exception=null(意思是我已经解决了异常,不需要再抛出了。)
但是,它向我抛出了一个异常。

【问题讨论】:

    标签: unity-container aop


    【解决方案1】:

    这不是它的工作原理。不要设置result.Exception,而是返回input.CreateMethodReturn(newReturnValues)。

    【讨论】:

    • 非常感谢。但是“input.CreateMethodReturn(newReturnValues)”无效,我没有找到type-newReturnValues。
    • 那不是类型,只是我坚持一个值。把你的返回值放在这里。如果是 void 方法被拦截,则将 null 放在那里。
    • newReturnValues 表示函数的返回值。假设 getNext() 抛出异常并且您不想重新抛出它,您将不得不从函数返回 some 值。
    • @ChrisTavares 非常感谢您的回答。所以知道,问题是如果返回类型是原始 (ByVal) 类型,我不能返回 null 如果我这样做,它返回时会导致另一个异常。如果返回 typeByVal,有没有办法解决这个问题或者我可以确定?
    • 如果是值类型,选择一个返回值。返回 0、-1 或 6.02e23。这取决于您,根据您的拦截行为及其预期目的,合理的响应是什么。您可以使用反射 API 来确定返回类型是什么以及要返回的潜在有效值(default 通常也是一个不错的选择)。
    猜你喜欢
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多