Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing and Deserializing Custom Exceptions in C#

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!!!

like image 730
Lalithaditya Kota Avatar asked Feb 05 '26 05:02

Lalithaditya Kota


1 Answers

The common language runtime throws SerializationException if any type in the graph of objects being serialized does not have the SerializableAttribute attribute applied.

Here: https://learn.microsoft.com/en-us/dotnet/api/system.serializableattribute?view=net-6.0#remarks

Try removing the SerializableAttribute

like image 112
Zoidbergseasharp Avatar answered Feb 09 '26 08:02

Zoidbergseasharp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!