Skip to content

What's the recommended way to serialize a customized exception in .NET 8+ #101159

Closed

Description

@yanxurui

Due to rule SYSLIB0051: Legacy serialization support APIs are obsolete, we are not allowed to add [Serializable] attribute or implements ISerializable.GetObjectData. So, what's the recommended method to serialize a customized exception derived from Exception in .NET 8+?

DataContractJsonSerializer does not work for me:

namespace ConsoleApp4
{
    public class MyException : Exception
    {
        public string Name { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Create a Person object and serialize it to a JSON stream    
            var exception = new MyException();
            MemoryStream stream1 = new MemoryStream();
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MyException));
            ser.WriteObject(stream1, exception);

            // Show the JSON output  
            stream1.Position = 0;
            StreamReader sr = new StreamReader(stream1);
            Console.Write("JSON form of Person object: ");
            Console.WriteLine(sr.ReadToEnd());

            // Deserialize the JSON back into a new Person object  
            stream1.Position = 0;
            MyException exception2 = (MyException)ser.ReadObject(stream1);
        }
    }
}
Unhandled exception. System.Runtime.Serialization.InvalidDataContractException: Type 'ConsoleApp4.MyException' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required.
   at System.Runtime.Serialization.DataContracts.DataContract.DataContractCriticalHelper.ThrowInvalidDataContractException(String message, Type type)
   at System.Runtime.Serialization.DataContracts.DataContract.DataContractCriticalHelper.CreateDataContract(Type type)
   at System.Runtime.Serialization.DataContracts.DataContract.DataContractCriticalHelper.CreateDataContract(Int32 id, RuntimeTypeHandle typeHandle, Type type)
   at System.Runtime.Serialization.DataContracts.DataContract.DataContractCriticalHelper.GetDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type)
   at System.Runtime.Serialization.DataContracts.DataContract.GetDataContract(RuntimeTypeHandle typeHandle)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.get_RootContract()
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph)
   at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.WriteObject(Stream stream, Object graph)
   at ConsoleApp4.Program.Main(String[] args) in C:\work\my\repos\ConsoleApp10\ConsoleApp4\Program.cs:line 30

C:\work\my\repos\ConsoleApp10\ConsoleApp4\bin\Debug\net8.0\ConsoleApp4.exe (process 51064) exited with code -532462766.
Press any key to close this window . . .

Activity

  1. added
    untriaged
    on Apr 17, 2024
  2. danmoseley commented on Apr 17, 2024

    @danmoseley
    Contributor

    Could you say more about what you are serializing it for? Do you need to recreate the object exactly, or just essentially the ToString()? Also is this for arbitrary exception types?

  3. yanxurui commented on Apr 17, 2024

    @yanxurui
    Author

    @danmoseley Thanks for the quick reply. I have added you to an internal thread where you can find more details.

  4. osexpert commented on Apr 23, 2024

    @osexpert

    ISerializable.GetObjectData is perfectly usable both without [Serializable] and BinaryFormatter, so I don't understand why it was obsoleted (I could maybe have understood it if an alternative existed). Other rpc implementations that do not use BinaryFormatter or [Serializable] attribute, use ISerializable.GetObjectData, and now has to deal with this suddenly being obsoleted for no good reason.

  5. added
    binaryformatter-migration
    on May 29, 2024
  6. dotnet-policy-service commented on Jun 5, 2024

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-runtime
    See info in area-owners.md if you want to be subscribed.

  7. added
    needs-further-triage
    and removed
    untriaged
    on Jun 24, 2024
  8. added
    documentation
    and removed
    needs-further-triage
    on Jul 27, 2024
  9. added this to the 9.0.0 milestone on Jul 27, 2024
  10. ostrink commented on Sep 25, 2024

    @ostrink

    Could you say more about what you are serializing it for? Do you need to recreate the object exactly, or just essentially the ToString()? Also is this for arbitrary exception types?

    In my case, I've implemented a proxy across process boundaries. I need to get the original exception from one process to another. Previously, I would have used BinaryFormatter, but as we know, that is no longer supported. Any suggestions for how best to recreate the exception on the other side of the proxy?

  11. jeffhandley commented on Oct 8, 2024

    @jeffhandley
    Member

    Thank you @ostrink. I'm closing this to merge it with #43482, which will be addressed via documentation.

  12. locked and limited conversation to collaborators on Nov 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-System.Runtimebinaryformatter-migrationdocumentation

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions