开发者

Extension method to Exception requiring dynamic generic type

This question has been asked in different ways before, but the answers don't help me, because (1开发者_运维问答) I don't have control over the built-in Exception classes, and (2) Activator.CreateInstance() returns an object/instance, where I need a true dynamic type.

I'm trying to create an extension method that allows me to throw a FaultException out of my WCF service, based off the exception I catch. For example:

try {
    ...
}
catch (ArgumentNullException exc) {
    throw new FaultException<ArgumentNullException>(exc);
}

is straight-forward. But if I want to extend this in a general way, I'd use an extension class, like:

try {
    ...
}
catch (Exception exc) {
    exc.ThrowFaultException();
}

Where I get hung up, of course, is the implementation of the extension method:

public static void ThrowFaultException(this Exception exc) {

    //  Gives me the correct type...
    Type exceptionType = exc.GetType();

    //  But how the heck do I use it?
    throw new FaultException<???>(exc);
}

The answers here and here don't help. Any ideas?


Try this:

public static void ThrowFaultException<TException>(this TException ex) where TException : System.Exception
{
    throw new FaultException<TException>(ex);
}


   public static void ThrowFaultException(this Exception exc)
    {
        //  Gives me the correct type...
        Type exceptionType = exc.GetType();
        var  genericType = typeof(FaultException<>).MakeGenericType(exceptionType);
        //  But how the heck do I use it?
        throw (Exception)Activator.CreateInstance(genericType, exc);
    }


You don't need to cast the object returned by Activator.CreateInstance to FaultException<?> to throw it. Casting it to Exception is enough:

var type = typeof(FaultException<>).MakeGenericType(exc.GetType());

throw (Exception)Activator.CreateInstance(type, exc);

I wouldn't throw the exception in ThrowFaultException though:

try
{
    ...
}
catch (Exception e)
{
    throw e.WrapInFaultException();
}

public static Exception WrapInFaultException(this Exception e)
{
    var type = typeof(FaultException<>).MakeGenericType(e.GetType());

    return (Exception)Activator.CreateInstance(type, e);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜