Use exceptions or error enum?
Hi there
I'm currently designing a C# wrapper API for a web API and I'm not entirely sure how I should treat errors.
My wrapper basically returns responses in neat structs that the end user then can use however they please. But should possible errors be a part of that struct?
Some pseudo code to hopefully explain what options I have
I'm just not sure what is the most desired for the average .NET developer. I've heard exceptions have some performance overhead when throwing. The library is also designed to be used in Unity and from my experience in Unity, you really don't catch exceptions as often.
5 Replies
Exceptions do absolutely have some overhead when throwing. What you're describing here is the result pattern, in which you use a type to describe something which is either a successful value or an error.
Imo this is a very good use-case for the result pattern and will make your code way safer.
Yeah, I do really like the result pattern and would use it everywhere if it was a standard C# feature lol
I just don't feel like providing a new result type for every library I make (because I can't use NuGet, thanks Unity! 🙄 )
Yeahhh that's understandable
I'm also a bit hesistant to use it because it basically forces the consumer to use a pattern that may be alien to them. Exceptions is a standard part, but heavy. Results is not a C# standard but faster and safer...
But it may be better for their own sake to use the result pattern? haha
Imo using a non-standard pattern like this is fine