SandyShores SandyShores - 27 days ago 6
C# Question

What datatype is the Exception variable?

I have a code running where I need to save the exceptions into a SQL Server database using the following code:

public void AcieveSomething()
{
//Datatype Declarations
string ApplicationName = "App_Name";
string ClassName = "Class_Name";
string MethodName = "Achieve Something";

try
{
//Main part of the code
}

catch(Exception ex)
{
//Calling function to input the error into DB
ErrorLog.WriteErrorLog(ex, ApplicationName, ClassName, MethodName);
}
}


If I'm going to put the
ex
value into DB, what is the datatype for
Exception ex;
in SQL Server database ?

Answer

As @Liath said, Exception inherits from System.Object. Any error or warning coming back from the database will usually be of the type SqlException.

A good ideal would be to serialize the Exception object to XML and store it as XML in the database.

To do this, it's best to create your own Exception type that encapuslates the information that you want to store, something like this:

[Serializable]
public class StorableException
{
    public DateTime TimeStamp { get; set; }
    public string Message { get; set; }
    public string StackTrace { get; set; }

    public StorableException()
    {
        this.TimeStamp = DateTime.Now;
    }

    public StorableException(string Message) : this()
    {
        this.Message = Message;
    }

    public StorableException(System.Exception ex) : this(ex.Message)
    {
        this.StackTrace = ex.StackTrace;
    }

    public override string ToString()
    {
        return this.Message + this.StackTrace;
    }
}

Then you can do:

catch(Exception ex)
{
    StorableException s = new StorableException(ex);

    //now we can serialize it
    XmlSerializer xsSubmit = new XmlSerializer(typeof(StorableException));
    StringWriter sww = new StringWriter();
    XmlWriter writer = XmlWriter.Create(sww);
    xsSubmit.Serialize(writer, s);
    var xml = sww.ToString();

    //now save the xml file to a column in your database

    ErrorLog.WriteErrorLog(ex, ApplicationName, ClassName, MethodName);
}