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.
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).
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.
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) { } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With