|
Sure. If your function does things internally that might return errors, the normal thing to do is have your function also potentially return an error, namely the first error it finds. If you call a function the error of which isn't a big deal to your function, you'd normally check the return value to make sure it meets your expectations. If it does, fine -- proceed accordingly. If it doesn't, then send the error up the chain. So -- totally bogus example -- say you want to return the mod time of a file or, if the file doesn't exist, the epoch. The file not existing is an error, but not one you'd abort on; other file errors though would be problematic: // ModOrEpoch returns the modification time of the file at path, or the epoch
// time if there is no such file. Unexpected file conditions are returned
// as errors.
func ModOrEpoch(path string) (time.Time, error) {
epoch := time.Unix(0, 0)
info, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return epoch, nil
}
return time.Now(),
fmt.Errorf("File error for %s: %s", path, err.Error())
}
if info.IsDir() {
return time.Now(),
fmt.Errorf("File is a directory: %s", path)
}
return info.ModTime(), nil
}
https://play.golang.org/p/AMSJMV3tksI suppose it's possible you might really, really not care about an error, but that would be extremely un-idiomatic in Go. And, I would argue, a very bad habit in any language where the error could possibly be other than what you expect; sort of like try { foobar(); } catch(e) { /* global thermonuclear war? */ }
The thing that bugs me about seeing the errors ignored in official docs is that the Go world puts a lot of emphasis on writing idiomatic code, and the Go "idiom" is much less flexible than, say, Perl's. You might reasonably look to the official documentation to learn what is and isn't idiomatic. And you would hopefully figure out soon enough that ignoring errors isn't, but then again you might not. |
Assuming that ModOrEpoch was being used to populate a mouseover somewhere on a ui that literally could not be less important, any error propagation is going to be degrading service considerably more than swallowing any error and returning epoch time.
Unless there is (and there could well be) a subset of errors which actually cause serious concerns but don't cause errors in any other function in the application? Do you have any examples/thoughts of what that might entail. :)