C
C#•7mo ago
Hertzole

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
MyResponse response = await Serializer.Deserialize(json);
if(response.message == "Invalid Credentials")
{
// A:
throw new MyAuthException("Invalid credentials");
// B:
return new MyResponse(success: false, errror: MyErrors.InvalidCredentials);
}
MyResponse response = await Serializer.Deserialize(json);
if(response.message == "Invalid Credentials")
{
// A:
throw new MyAuthException("Invalid credentials");
// B:
return new MyResponse(success: false, errror: MyErrors.InvalidCredentials);
}
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
Thinker
Thinker•7mo ago
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.
Hertzole
Hertzole•7mo ago
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! 🙄 )
Thinker
Thinker•7mo ago
Yeahhh that's understandable
Hertzole
Hertzole•7mo ago
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
Thinker
Thinker•7mo ago
Imo using a non-standard pattern like this is fine