如何序列化在C#中的异常对象?异常、对象、序列化

2023-09-02 10:24:37 作者:後會無期

我试图序列化在C#中的异常对象。但是,看来这是不可能的,因为Exception类没有标记为可序列化。有没有办法来解决呢?

I am trying to serialize an Exception object in C#. However, it appears that it is impossible since the Exception class is not marked as Serializable. Is there a way to work around that?

如果出了应用程序的执行过程中错了,我希望能与所发生的异常通知。

If something goes wrong during the execution of the application, I want to be informed with the exception that occurred.

我的第一个反应就是序列化。

My first reflex is to serialize it.

推荐答案

我以前所做的就是创建一个自定义错误类。这封装了一个异常的所有相关信息,是XML序列化。

What I've done before is create a custom Error class. This encapsulates all the relevant information about an Exception and is XML serializable.

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

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

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

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

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