我运行的代码需要使用以下代码将异常保存到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/