Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 981
Martin Avatar asked Jan 28 '09 04:01

Martin


People also ask

Do exceptions need to be serializable?

Exceptions should be serializable so that they can automatically be marshalled across application domains or threads. At a minimum, you should mark your custom exception as serializable and implement the four basic constructors shown below. (This example shows a custom exception type that has no custom data).

What is serialization exception?

SerializationException(String, Exception) Initializes a new instance of the SerializationException class with a specified error message and a reference to the inner exception that is the cause of this exception.


1 Answers

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) { } } 
like image 162
David Crow Avatar answered Sep 19 '22 17:09

David Crow