Hacker News new | ask | show | jobs
by ethbr1 764 days ago
C# is pretty hard-nosed about serialization.

E.g. My discovery the other day that out of the box C# System.Text.Json can't serialize System.Exception without writing a custom serializer [0] (since 2020, because .NET fix speed...). NewtonSoft handles it fine. (Had wanted a quick-and-dirty debugging dump of properties)

[0] https://github.com/dotnet/runtime/issues/43026

1 comments

A serializer cannot make a reasonable assumption about how an exception should be serialized on the user's behalf, let alone deserialized. Newtonsoft had and still has quite a few problematic defaults where people can inadvertently weaken privacy and security of the implementation, which System.Text.Json is opinionated in solving.

If you are okay with risks that come from including exception's message in data sent over the network (e.g. not publicly exposed), then defining a custom converter is trivial (it's like 10-15 lines and adding it to serializer options), or you could simply .ToString/.Message it and include that in the payload instead. It's a minute thing.

As for exception deserialization, that's a gross feature misuse and not something that should be done.

To me, it feels like an abuse of "you shouldn't be doing that"-ism.

A serializer should generate a sane serialization of whatever I throw at it. Or at least have an option that allows me to force that.

If I then choose to send that serialization somewhere unreasonable, that's on me.

In my case, I was hacking in C#-on-top-of-another-environment, so didn't have full access to reimplement stuff, without jumping through additional hoops.

That said, absolutely agreed on de-serialization, as larger opportunities for footguns abound.