Skip to content

Add InterceptorException#8

Open
huazhikui wants to merge 1 commit intojiangjinnan:masterfrom
huazhikui:master
Open

Add InterceptorException#8
huazhikui wants to merge 1 commit intojiangjinnan:masterfrom
huazhikui:master

Conversation

@huazhikui
Copy link

@huazhikui huazhikui commented Mar 27, 2019

增加一个异常类型,通过其RequireThrow属性判断是否需要抛出异常。

用途:可通过此异常结合自定义IInterceptorProviderResolver的实现完成类似参数拦截的功能

例如

public virtual string Test([NotNull] string name)

当name参数为空值时将抛出异常

registry.Add(new MethodParameterInterceptorAttribute(), method =>
{
    var parameters = method.GetParameters();
    var result = parameters.Any(x => x.GetCustomAttributes(false).Any(y => y is ParameterInterceptorAttribute));
    return result;
});
   public class MethodParameterInterceptorAttribute : InterceptorAttribute
    {
        public override void Use(IInterceptorChainBuilder builder)
        {
            builder.Use<ParameterInterceptor>(Order);
        }
    }
    [AttributeUsage(AttributeTargets.Parameter)]
    public abstract class ParameterInterceptorAttribute : Attribute, IParameterInterceptorAttribute
    {
      
        public abstract void PreHandleParameter(ParameterInfo parameter, object parameterValue, InvocationContext context);
    }
public class NotNullAttribute : ParameterInterceptorAttribute
    {
        public override void PreHandleParameter(ParameterInfo parameter, object parameterValue, InvocationContext context)
        {
            Guard.ArgumentNotNull(parameterValue, parameter.Name);
        }
    }
...
try
{
    interceptorAttribute.PreHandleParameter(item.Parameter, item.ParameterValue, context);
} catch (Exception ex)
{
    throw new InterceptorException("'{0}'方法的'{1}'参数拦截器'{2}'处理异常".Fill($"{context.Method.DeclaringType.FullName}.{context.Method.Name}", item.Parameter.Name, interceptor.GetType().Name), ex, false);
}
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

Comments