c# - Exception变量是什么数据类型?

标签 c# sql-server exception

我运行的代码需要使用以下代码将异常保存到SQL Server数据库中:

    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);
       }
   }


如果要将ex值放入数据库,SQL Server数据库中Exception ex;的数据类型是什么?

最佳答案

正如@Liath所说,Exception继承自System.Object。从数据库返回的任何错误或警告通常将为SqlException类型。

理想的做法是将Exception对象序列化为XML,并将其作为XML存储在数据库中。

为此,最好创建自己的Exception类型来封装要存储的信息,如下所示:

[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;
    }
}


然后,您可以执行以下操作:

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);
}

关于c# - Exception变量是什么数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27599270/

相关文章:

sql - 如何检查字符串是否是唯一标识符?

ruby-on-rails - Rails 异常处理

c# - Visual Studio 中是否有击键来切换中断所有 CLR 异常,第一次机会?

c# - .NET Web API - ModelState 的错误响应

c# - 使用流通过 Json.NET 创建 BSON 字节数组(文件格式)

c# - ASP.NET Web 应用程序无法使用自定义 Bootstrap 正确显示内容

Python:如何以替代方式处理任何未处理的异常?

c# - SystemSounds.Beep.Play 不发出任何声音

sql - "Select Top 10, then Join Tables",而不是 "Select Top 10 from Joined Tables"

sql-server - 行 'not in' 和行 'in' 不等于表中的总行数