Search code examples
c#.netpostsharp

Setting inner exception with activator, C#, Postsharp


Writing postsharp aspect that wrappes A type exception and outputs it as B type. 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);

I get error that xxxx type exception doesn't have constructor defined for it, how to get around this? Do i have to use some kind of reflection trick to write private field?


Solution

  • Use Type.GetConstructor(Type[]) to get the appropriate Exception constructor. http://msdn.microsoft.com/en-us/library/h93ya84h.aspx

    Something like this:

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