异常变量是什么数据类型

本文关键字:数据类型 是什么 变量 异常 | 更新日期: 2023-09-27 18:34:51

>我有一个代码正在运行,我需要使用以下代码将异常保存到 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);
}

Exception 是一个继承自 System.Object 的类,如果要将其持久化到数据库中,则需要确定要存储哪些属性并将它们添加到不同的列中(或在另一个答案中使用序列化方法(。

通常,开发人员使用的属性是Message,StackTrace和InnerException,尽管从Exception派生的其他类型可能还有其他类型。

Message 和 StackTrace 都是字符串,因此 nvarchar(或其他文本字段(适合存储它们。由于 InnerException 是另一个异常(并且可能有它自己的内部异常(,最好的方法是将 InnerException 添加为例外表中自己的行。

将异常序列化为 XML 到数据库中时,回查询会很痛苦。将 Exception.InnerException 写入 nvarchar(max( 更方便。