Exception and Reflection

2019-05-31 15:27发布

问题:

The web service has SoapExtension, which contains an error handler and serializing error in a format xml.

<? Xml version = "1.0" encoding = "utf-8" standalone = "yes"?>
<Exception Type="System.NullReferenceException"> Exception text. </ Exception>

How to make error handler, which call error of "Type"? E.g.:

Type _type = Type.GetType(doc.DocumentElement.Attributes["Type"].Value);

It must to call NullReferenceException.

回答1:

You need to provide the fully-qualified name, i.e. "System.NullReferenceException".

In this particular case, that's enough - because NullReferenceException is in mscorlib. However, if you need other exceptions - such as ConstraintException, which lives in the System.Data assembly - you'd need to provide the full assembly name too. Type.GetType(string) only looks in the currently executing assembly and mscorlib for type names which don't specify the assembly.

EDIT: Here's a short but complete program which works:

using System;
using System.Reflection;

class Test
{
    static void Main()
    {
        string typeName = "System.NullReferenceException";
        string message = "This is a message";
        Type type = Type.GetType(typeName);
        ConstructorInfo ctor = type.GetConstructor(new[] { typeof(string) });
        object exception = ctor.Invoke(new object[] { message });
        Console.WriteLine(exception);
    }
}


回答2:

I use such code:

public static Exception Invoke(string soapMessage) {
    //...            
    string _message = doc.DocumentElement.InnerText;
    Type_type = Type.GetType(doc.DocumentElement.Attributes["Type"].Value);
    ConstructorInfo constructor = _type.GetConstructor(new[] {typeof (string), _type.GetType()});
    try {
        Exception ctor = (Exception)constructor.Invoke(new object[] { _message, _type });
    } catch (Exception ex) {
        return ex;
    }
    return null;
}