How to serialize an Exception object in C#?

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.

87979 次浏览

I'm not sure why you would want to serialize the exception...

If I did want to do what you specify, I'd create a custom Exception class that implements ISerializable. You can choose to make it child of Exception or you could have it be a completely custom class that only has and does what you need.

If you're trying to serialize the exception for a log, it might be better to do a .ToString(), and then serialize that to your log.

But here's an article about how to do it, and why. Basically, you need to implement ISerializable on your exception. If it's a system exception, I believe they have that interface implemented. If it's someone else's exception, you might be able to subclass it to implement the ISerializable interface.

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) { }
}

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.

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;
}
}

Create a protected constructor like this (also you should mark your Exception class [Serializable]):

protected MyException(System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context):base(info,context)
{
}

mson wrote: "I'm not sure why you would want to serialize the exception..."

I serialize exceptions to bubble up the exception, through a web service, to the calling object that can deserialize, then rethrow, log or otherwise handle it.

I did this. I simply created a Serializable wrapper class that replaces the IDictionary with a serializable alternative (KeyValuePair array)

/// <summary>
/// A wrapper class for serializing exceptions.
/// </summary>
[Serializable] [DesignerCategory( "code" )] [XmlType( AnonymousType = true, Namespace = "http://something" )] [XmlRootAttribute( Namespace = "http://something", IsNullable = false )] public class SerializableException
{
#region Members
private KeyValuePair<object, object>[] _Data; //This is the reason this class exists. Turning an IDictionary into a serializable object
private string _HelpLink = string.Empty;
private SerializableException _InnerException;
private string _Message = string.Empty;
private string _Source = string.Empty;
private string _StackTrace = string.Empty;
#endregion


#region Constructors
public SerializableException()
{
}


public SerializableException( Exception exception ) : this()
{
setValues( exception );
}
#endregion


#region Properties
public string HelpLink { get { return _HelpLink; } set { _HelpLink = value; } }
public string Message { get { return _Message; } set { _Message = value; } }
public string Source { get { return _Source; } set { _Source = value; } }
public string StackTrace { get { return _StackTrace; } set { _StackTrace = value; } }
public SerializableException InnerException { get { return _InnerException; } set { _InnerException = value; } } // Allow null to be returned, so serialization doesn't cascade until an out of memory exception occurs
public KeyValuePair<object, object>[] Data { get { return _Data ?? new KeyValuePair<object, object>[0]; } set { _Data = value; } }
#endregion


#region Private Methods
private void setValues( Exception exception )
{
if ( null != exception )
{
_HelpLink = exception.HelpLink ?? string.Empty;
_Message = exception.Message ?? string.Empty;
_Source = exception.Source ?? string.Empty;
_StackTrace = exception.StackTrace ?? string.Empty;
setData( exception.Data );
_InnerException = new SerializableException( exception.InnerException );
}
}


private void setData( ICollection collection )
{
_Data = new KeyValuePair<object, object>[0];


if ( null != collection )
collection.CopyTo( _Data, 0 );
}
#endregion
}

Here is a very useful class for serializing an Exception object into an XElement (yay, LINQ) object:

http://seattlesoftware.wordpress.com/2008/08/22/serializing-exceptions-to-xml/

Code included for completeness:

using System;
using System.Collections;
using System.Linq;
using System.Xml.Linq;
 

public class ExceptionXElement : XElement
{
public ExceptionXElement(Exception exception)
: this(exception, false)
{ ; }
 



public ExceptionXElement(Exception exception, bool omitStackTrace)
: base(new Func<XElement>(() =>
{
// Validate arguments
if (exception == null)
{
throw new ArgumentNullException("exception");
}
            

// The root element is the Exception's type
XElement root = new XElement(exception.GetType().ToString());
if (exception.Message != null)
{
root.Add(new XElement("Message", exception.Message));
}
            

// StackTrace can be null, e.g.:
// new ExceptionAsXml(new Exception())
if (!omitStackTrace && exception.StackTrace != null)
{
vroot.Add(
new XElement("StackTrace",
from frame in exception.StackTrace.Split('\n')
let prettierFrame = frame.Substring(6).Trim()
select new XElement("Frame", prettierFrame))
);
}
            

// Data is never null; it's empty if there is no data
if (exception.Data.Count > 0)
{
root.Add(
new XElement("Data",
from entry in exception.Data.Cast<DictionaryEntry>()
let key = entry.Key.ToString()
let value = (entry.Value == null) ? "null" : entry.Value.ToString()
select new XElement(key, value))
);
}
            

// Add the InnerException if it exists
if (exception.InnerException != null)
{
root.Add(new ExceptionXElement(exception.InnerException, omitStackTrace));
}
return root;
})())
{ ; }
}

This is an old thread, but worthy of another answer.

@mson wondered why anyone would want to serialize an Exception. Here's our reason for doing it:

We have a Prism/MVVM application with views in both Silverlight and WPF, with the Data Model in WCF services. We want to be sure that data access and updates occur without error. If there is an error, we want to know about it immediately, and let the user know that something may have failed. Our applications will pop a window informing the user of a possible error. The actual exception is then e-mailed to us, and stored in SpiceWorks for tracking. If the error occurs on a WCF service, we want to get the full exception back to the client so this process can happen.

Here is the solution I came up with that can be handled by both WPF and Silverlight clients. The methods below a in a "Common" class library of methods used by multiple applications in every layer.

A byte array is easily serialized from a WCF service. Pretty much any object can be converted into a byte array.

I started with two simple methods, Object2Bytes and Bytes2Object. These convert any object to a Byte array and back. NetDataContractSerializer is from the Windows version of the System.Runtime.Serialization Namespace.

Public Function Object2Bytes(ByVal value As Object) As Byte()
Dim bytes As Byte()
Using ms As New MemoryStream
Dim ndcs As New NetDataContractSerializer()
ndcs.Serialize(ms, value)
bytes = ms.ToArray
End Using
Return bytes
End Function


Public Function Bytes2Object(ByVal bytes As Byte()) As Object
Using ms As New MemoryStream(bytes)
Dim ndcs As New NetDataContractSerializer
Return ndcs.Deserialize(ms)
End Using
End Function

Originally, we would return all results as an Object. If the object coming back from the service was a byte array, then we knew it was an exception. Then we would call "Bytes2Object" and throw the exception for handling.

Trouble with this code is, it's incompatible with Silverlight. So for our new applications I kept the old methods for hard-to-serialize objects, and created a pair of new methods just for exceptions. DataContractSerializer is also from the System.Runtime.Serialization Namespace, but it is present in both the Windows and Silverlight versions.

Public Function ExceptionToByteArray(obj As Object) As Byte()
If obj Is Nothing Then Return Nothing
Using ms As New MemoryStream
Dim dcs As New DataContractSerializer(GetType(Exception))
dcs.WriteObject(ms, obj)
Return ms.ToArray
End Using
End Function


Public Function ByteArrayToException(bytes As Byte()) As Exception
If bytes Is Nothing OrElse bytes.Length = 0 Then
Return Nothing
End If
Using ms As New MemoryStream
Dim dcs As New DataContractSerializer(GetType(Exception))
ms.Write(bytes, 0, bytes.Length)
Return CType(dcs.ReadObject(ms), Exception)
End Using
End Function

When no errors occur, the WCF service returns 1. If an error occurs, it passes the Exception to a method that calls "ExceptionToByteArray," then generates a unique integer from the present time. It uses that integer as a key to cache the byte array for 60 seconds. The WCF service then returns the key value to the client.

When the client sees that it got back an integer other than 1, it makes a call to the Service's "GetException" method using that key value. The service fetches the byte array from cache and sends it back to the client. The client calls "ByteArrayToException" and processes the exception as I described above. 60 seconds is plenty of time for the client to request the exception from the service. In less than a minute, the server's MemoryCache is cleared.

I think this is easier than creating a custom Exception class. I hope this is a help to somebody later on.

[Serializable]
public class CustomException: Exception
{
public CustomException: ( Exception exception ) : base(exception.Message)
{
Data.Add("StackTrace",exception.StackTrace);
}
}

To serialize your custom exception:

JsonConvert.SerializeObject(customException);

I faced a similar problem where I needed to log the details of an Exception thrown in my application, however, it contained a non-serializable member, hence it couldn't be serialized.

As a workaround the .ToString() Method gets called on the Exception which returns a string containing details of the Exception.

string bar;


if (foo is Exception exception)
{
bar = exception.ToString();
}

Source: Exception.ToString Method