How to serialize an Exception object in C#?
Create a custom Exception class with the [Serializable()] attribute. Here's an example taken from the MSDN:
[Serializable()]
public class InvalidDepartmentException : System.Exception
{
public InvalidDepartmentException() { }
public InvalidDepartmentException(string message) : base(message) { }
public InvalidDepartmentException(string message, System.Exception inner) : base(message, inner) { }
// Constructor needed for serialization
// when exception propagates from a remoting server to the client.
protected InvalidDepartmentException(System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
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;
}
}
The Exception class is marked as Serializable and implements ISerializable. See MSDN: http://msdn.microsoft.com/en-us/library/system.exception.aspx
If you are attempting to serialize to XML using the XmlSerializer
, you will hit an error on any members that implement IDictionary
. That is a limitation of the XmlSerializer, but the class is certainly serializable.