San*_*ger 1 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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我要将ex值放入DB,Exception ex;SQL Server数据库中的数据类型是什么?
正如@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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
898 次 |
| 最近记录: |