11 ms·
The snippet used in these examples is almost never what you actually write in real code. You will almost always annotate the error, e.g. result, err := com
by sagichmal 7y ago
The snippet used in these examples is almost never what you actually write in real code. You will almost always annotate the error, e.g.
result, err := computeVector(input)
if err != nil {
return nil, fmt.Errorf("error computing vector: %w", err)
}
But that's a bit unwieldy to write in an article or talk.
- tsimionescu 7y agoThat's still not error handling. Error handling would look something like this: for err := callService(); err != nil { logger.Info("Retrying...") } Or value, err := readValueFromFile("abc.conf") if err != nil { value = getDefault() } etc.
- jkachmar 7y ago> The snippet used in these examples is almost never what you actually write in real code. This statement is categorically false, and I would encourage you to search GitHub for `return err` under the Go language. There are 200k+ code results, and a quick survey of the first few pages shows plain ol' `return err` to be _quite_ common.
- monocasa 7y agoYou've just removed all of the machine parsable context of the error, guaranteeing that downstream code can't make an intelligent decision.
- DuskStar 7y agoThat's what errors.Is() is for.
- sagichmal 7y agoNo, I didn't. https://golang.org/pkg/errors https://golang.org/pkg/errors
- monocasa 7y agoI mean, that's a not in the standard library, and it's a library that's literally already in maintenance mode. Edit: you also deleted the context of your call. You didn't create an error type for Unwrap to match on. That means that downstream code only has extremely primitive errors to match on, with the context of the call gone. Just because you can track down the EOF error, doesn't mean that code calling this can do anything useful with that. 'Socket closed unexpectedly' is way less useful than 'Unable to update user record'.
- sagichmal 7y agoPackage errors is indeed a part of the standard library.
- tsimionescu 7y agoYes, they were wrong about that. But they were right about it losing error context. Basically errorf can only help you bubble up the lowest level error in a machine readable way. You have to write your own error type if you want to let code handle the higher level errors.
- erik_seaberg 7y agoThat can and should be generated; it's not as if the machine doesn't know which function failed. We don't force human beings to plow through all the rote instructions that set up a stack frame or invoke an object's implementation of a method, and for the same reason we shouldn't force them to plow through the rote instructions that bubble an error toward the handler. When errors exist in your problem domain, manipulating them becomes part of the language's job, and nearly every language from the last thirty years acknowledges that.