如何通过IInterceptionBehavior吞掉异常?
我有一个像blow这样的IInterceptionBehavior:
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; } }
}
无论我是否将其放在方法上,异常总是抛出。有人可以帮助我吗?
I have a IInterceptionBehavior like blow:
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; } }
}
Regardless of whether I put it upon methods or not, exception throw always. Anyone can help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
代码看起来不错,但您没有显示如何注册拦截以及如何调用对象。
假设正在调用拦截,那么如果我猜测调用的方法会返回值类型,并且 IMethodReturn.ReturnValue 为 null,这会导致 NullReferenceException。
如果是这种情况,那么返回值类型的默认值也许可以解决您的问题:
The code looks OK but you haven't shown how the interception is registered and how the object is being called.
Assuming that interception is being called then if I were to guess it would be that that the method invoked returns a value type and
IMethodReturn.ReturnValue
is null which is causing aNullReferenceException
.If that is the case then perhaps returning the default value for a value type would solve your issue: