简体   繁体   English

使用激活器C#,Postsharp设置内部异常

[英]Setting inner exception with activator, C#, Postsharp

Writing postsharp aspect that wrappes A type exception and outputs it as B type. 编写包装A类型异常并将其输出为B类型的postharsh方面。 This is common pattern in some cases so this should remove pretty much of boilerplate. 在某些情况下,这是常见的模式,因此应该删除很多样板。 Question is, how to set inner exception when creating exception with activator? 问题是,使用激活器创建异常时如何设置内部异常?

namespace PostSharpAspects.ExceptionWrapping
{
    [Serializable]
    public class WrapExceptionsAttribute : OnMethodBoundaryAspect
    {
        private readonly Type _catchExceptionType;
        private readonly Type _convertToType;

        public WrapExceptionsAttribute(Type catchTheseExceptions, Type convertThemToThisType)
        {
            _catchExceptionType = catchTheseExceptions;
            _convertToType = convertThemToThisType;
        }

        public override void OnException(MethodExecutionArgs args)
        {
            if (args.Exception.GetType() == _catchExceptionType)
            {
                throw (Exception) Activator.CreateInstance(_convertToType);
            }
        }
    }
}

If i try set inner exception with: throw (Exception) Activator.CreateInstance(_convertToType, args.Exception); 如果我尝试使用以下方法设置内部异常:throw(Exception)Activator.CreateInstance(_convertToType,args.Exception);

I get error that xxxx type exception doesn't have constructor defined for it, how to get around this? 我收到xxxx类型异常没有为其定义构造函数的错误,如何解决呢? Do i have to use some kind of reflection trick to write private field? 我是否必须使用某种反射技巧来写私有字段?

Use Type.GetConstructor(Type[]) to get the appropriate Exception constructor. 使用Type.GetConstructor(Type [])获得适当的Exception构造函数。 http://msdn.microsoft.com/en-us/library/h93ya84h.aspx http://msdn.microsoft.com/zh-CN/library/h93ya84h.aspx

Something like this: 像这样:

throw (Exception)_convertToType
    .GetConstructor(new Type[]{ typeof(string), typeof(Exception) })
    .Invoke(new object[]{ _catchExceptionType });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM