5 ms·
What if you want to log, then emit some time series data? Is chaining+traits+wrappers+map_err truly less complex than a conditional: if BAD { Log()
by politician 5y ago
What if you want to log, then emit some time series data?
Is chaining+traits+wrappers+map_err truly less complex than a conditional:
if BAD {
Log()
Metric1()
Metric2()
}
- nicoburns 5y agoIf 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.
- chrismorgan 5y agoAnd 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.
- wavemode 5y agoThe 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.