Serializing and Deserializing Custom Exceptions in C#

Viewed 547

I'm currently working on exceptions and I've created a custom exception which implements the parent Exception class.

The problem arises when I try to Serialize or Deserialize such a custom exception.

The error is as follows : "System.Runtime.Serialization.SerializationException: 'Member 'InnerException' was not found.'"

I've referred to many sources on the internet, but was not able to fix the issue. I'm attaching the code with this body.

[Serializable]
public class CustomException : Exception
{
    public const string DefaultExceptionDescription = "temp";

    public string ExceptionDescription { get; set; }

    public string ReferenceId { get; private set; } = "temp";

    public CustomException(string ExceptionDescription = DefaultExceptionDescription)
    {
        ExceptionDescription = ExceptionDescription;
    }

    [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
    protected CustomException(SerializationInfo info, StreamingContext context) : base(info, context)
    {
        if (info != null)
        {
            ExceptionDescription = info.GetString(nameof(ExceptionDescription));
            ReferenceId = info.GetString(nameof(ReferenceId));
        }
    }

    [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
    public override void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        if (info != null)
        {
            info.AddValue(nameof(ExceptionDescription), ExceptionDescription);
            info.AddValue(nameof(ReferenceId), ReferenceId);
        }

        base.GetObjectData(info, context);
    }
}

Thanks in Advance!!!

1 Answers
Related