Search code examples
c#web-servicessoapwsdlblackboard

Extending Exception partial class


I'm using a sample SOAP code generated by wsdl.exe. The object lastError is declared like this:

private Exception lastError;

Visual Studio is giving error on build on this line

String msg = lastError.Message;

saying

'Exception' does not contain a definition for 'Message' and no extension method 'Message' accepting a first argument of type 'Exception' could be found (are you missing a using directive or an assembly reference?) :

The Exception class generated by wsdl.exe looks like this:

/// <remarks/>
[System.Xml.Serialization.XmlIncludeAttribute(typeof(NestedException))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(PersistenceException))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(BbSecurityException))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://gradebook.ws.blackboard")]
public partial class Exception {

    private object exception1Field;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Exception", IsNullable=true)]
    public object Exception1 {
        get {
            return this.exception1Field;
        }
        set {
            this.exception1Field = value;
        }
    }
}

Solution

  • partial classes don't automatically extend any built-in or non-partial classes by virtue of a shared name. If you want the above Exception class to extend System.Exception, then the easiest way to do that is to add another partial class and extend it explicitly:

    (In some other file)

    public partial class Exception : System.Exception
    {
    
    }
    

    You should be aware of issues having a class named Exception though. Technically you shouldn't really catch the generic Exception, but if you had something like this in your namespace, you may not be catching the exception you think you are:

    public void SomeMethod()
    {
        try
        {
            DoSomethingThatExcepts();
        }
        catch (Exception e)
        {
            //You are actually catching the defined Exception, not System.Exception
        }
    }
    

    So anywhere you use System.Exception you may have to fully qualify the name.