tags:

views:

84

answers:

2

I'm logging errors and sending myself the exception logs! Like the following code

    private void ExceptionForm_Load(object sender, EventArgs e)
    {
        Type exceptionType = _exception.GetType();

        txtErrorMessage.Text = _exception.ToString();

        if (exceptionType == typeof(Sybase.DataWindow.DbErrorException))
        {
             _exception = (Sybase.DataWindow.DbErrorException)_exception;

            txtErrorMessage.Text += "Exception SQL data:" +  exception;
        }

    }

Now the problem is this. if (exceptionType == typeof(Sybase.DataWindow.DbErrorException)) then _exception has extra properies like the SqlSyntax that went wrong (e.g. Update something from table) The problem is how do I display that data. It isnt in my exception so it seems. exceptiontype = DbErrorException but I can't seem to cast my _exception to it. Or is this bad practice? Or should I just delete everything and install the Exception Handling Application Block from MS?

+4  A: 

The problem isn't the cast - it's that your _exception variable is (presumably) of type Exception. You need to declare a new variable of the right type. Also, do you have any reason for using GetType() instead of "as" or "is"? What about derived exceptions? Try this:

private void ExceptionForm_Load(object sender, EventArgs e)
{
  DbErrorException specificException = _exception as DbErrorException;
  if (specificException != null)
  {
     txtErrorMessage.Text += "SqlSyntax=" + specificException.SqlSyntax;
  }
}
Jon Skeet
+1  A: 

That looks like it Jon! Didn't know about the "as" and "is". My _exception is indeed of the type Exception (because I send all my exceptions to this "log form"). Do I have to cast my exception all the data to a specific exception type if I want all the data? (e.g. webexception, socketexception)

Dean
The "as" effectively does a cast (when it's valid; when it's not it returns null). You only need to cast if none of the existing properties of Exception gives you enough information.
Jon Skeet
Thanks a million!ps; Funny fact that I read your threads in c# article a week ago randomly on the net :) Nice article!
Dean