3 ms·
I don't find this argument convincing: > I heavily disagree, as this will separate logic in at least 2 pieces, with the error being handled elsewhere. 1. Trig
by Hackbraten 2y ago
I don't find this argument convincing:
> I heavily disagree, as this will separate logic in at least 2 pieces, with the error being handled elsewhere.
1. Triggering and handling an error are two separate things. They can be on opposite sides of a library call, a process boundary, or a network boundary. Depending on the nature of the error, the logic that triggers it may be completely oblivious about how zo handle it.
2. Even if ignoring #1, returning an error code might propagate through the call stack, too, if call sites choose to do so.
My thoughts:
There is no one true best thing.
IMHO the most important thing is consistency. If you provide a Java API, then go ahead and throw exceptions, as is customary. In Go, return an idiomatic (result, err) tuple. If you're writing Typescript, consider using a union result type, maybe one that has a discriminating status field, if your failure mode is common enough that you prefer to force your callers to handle it. And if you're writing a C library, then go ahead and return EBADWIDGET or whatnot. Just keep it consistent to the rest of the code base and to developers's expectations.
If your language has both result types and exception types, and either is idiomatic, then ask yourself how strictly you want to force your clients to handle errors, and make your choice with that in mind.
- JohnFen 2y ago> There is no one true best thing. This is the right answer, in my opinion. Both methods have their own unique advantages and disadvantages, and so which is best depends on the situation.
- AnimalMuppet 2y agoBe consistent. Be consistent with what is standard/normal/customary for the language. If there is not one answer to that, at least be consistent in a codebase. Don't use error codes in some places and exceptions in others (and Maybe/Option types somewhere else). Pick one approach and stick with it, because if you don't, you'll get error-handling bugs at the boundaries where you switch from one approach to the other.