Re:Go’ing Insane: Endless Error Handling
by nicoburns on Tuesday September 14, 2021 @09:13AM
(#28524235)
If you're doing something more complex/involved in order to handle a particular error, then no I think a conditional/match is fine. It's the common case when you're not doing any special that the boilerplate becomes overwhelming.
Having said that, if you're outputting the same metrics for every error then a method that does this for you makes a lot more sense than repeating yourself all over the place.
Re:Go’ing Insane: Endless Error Handling
by chrismorgan on Tuesday September 14, 2021 @09:22AM
(#28524390)
And this is the beauty of chaining and extension traits: you can define your own “shorthands” without much trouble, because it’s all in the normal type system.
Remember also that .map_err() need not be significantly different from that if block; it can be essentially just a slightly different spelling:
let data = some_call().map_err(|e| {
log();
metric1();
metric2();
e
})?;
But I would draw your attention in all this to the fact that you’re dealing with algebraic data types, enums with data attached to the variants; this isn’t just some nullable data value and nullable error where you can say `if error { … }`; in order to get at the data, you need to handle the error. This has profound implications that, once you’re used to it, will shape your coding style and techniques even when you return to other languages.On things like metrics, I’d also mention that sometimes you may be better served by an RAII pattern, which can be made to be the rough equivalent of a defer statement in Go. Especially if you’re pairing start/end metrics, RAII can be particularly good at that.
Re:Go’ing Insane: Endless Error Handling
by wavemode on Thursday September 16, 2021 @07:23AM
(#28550326)
The commenter you're replying to is simply showing how logging and context and other things can be done in conjunction with the question mark syntax sugar. If you don't want to use the question mark at all, you're still free to explicitly pattern match on the Result object and do whatever complex thing you want with the error object before returning it.
Is chaining+traits+wrappers+map_err truly less complex than a conditional: