← Back to context

Comment by JCTheDenthog

21 hours ago

Simple example that I use often when writing API clients:

In current C# I usually do something like

public class ApiResponse<T> { public T? Response { get; set; } public bool IsSuccessful { get; set; } public ErrorResponse Error { get; set; } }

This means I have to check that IsSuccessful is true (and/or that Response is not null). But more importantly, it means my imbecile coworkers who never read my documentation need to do so as well otherwise they're going to have a null reference exception in prod because they never actually test their garbage before pushing it to prod. And I get pulled into a 4 hour meeting to debug and solve the issue as a result.

With union types, I can return a union of the types T and ErrorResponse and save myself massive headaches.

I think I get it but I'm not really sure what I'm gaining over exception types. With an intelligent use of exceptions I can easily specify the happy path and all the error paths separately which seems really nice to me, because usually the behaviour between those two outcomes is rather different.

  • > I think I get it but I'm not really sure what I'm gaining over exception types. With an intelligent use of exceptions I can easily specify the happy path and all the error paths separately which seems really nice to me, ...

    Until your coworker comes along and accidentally refactors the code to skip the exception catching and it suddenly blows up prod.

    With tagged unions you can't accidentally dereference to the underlying value without checking if it's actually proper data first.

    • > Until your coworker comes along and accidentally refactors the code to skip the exception catching and it suddenly blows up prod.

      can't my co-worker just use this pattern and discard an error result the same? I'd argue its easier as the stack wont unwind by default because the error is returned instead of thrown.

      1 reply →

  • Exceptions are significantly slower than normal control flow in C# (about 10,000 times slower). It's also pretty non-idiomatic in both C# and most other languages I've worked in to use exceptions instead of a switch statement or similar to handle an HTTP error code. Also there can be multiple possible non-error responses from an endpoint you need to differentiate between, and exceptions would make zero sense in that case.

    • > Also there can be multiple possible non-error responses from an endpoint you need to differentiate between

      Yeah, I'm mildly sold on this use-case to be fair. But I think I'll keep the unexpected errors as exceptions.