3 ms·
Go's error handling works well in small programs but there's a couple of issues. One is that it quickly becomes hard to find out where errors really came from.
by zimbatm 12y ago
Go's error handling works well in small programs but there's a couple of issues.
One is that it quickly becomes hard to find out where errors really came from. Consider this idiomatic code:
func MyFunc(input int) (output int, err error) {
if output, err = someOtherFuncA(input); err != nil {
return
}
if output, err = someOtherFuncB(output); err != nil {
return
}
// ...
}
If MyFunc returns an error it's not possible to know where it came from unless you know all about someOtherFuncA and someOtherFuncB and they return different kind of errors.
What's missing from the stdlib is a utility that wraps errors to reproduce what's essentially a backtrace. `return wrapError("someOtherFuncA", err)`
The other issue is that (error) doesn't tell you what kind of errors are going to be returned. It's often useful to be able to classify errors as to respond to them accordingly. IO errors might be retryable but data-structure errors might be not. In the stdlib they use value comparison as a trick to classify errors combined with documentation of what exactly will be returned.
- gizzlon 12y agoThink the point i to handle errors wherever they're best handled. Sometimes that means returning it and sometimes it means handling it right away. I've written code with this style of error-handling in Perl 5, and I think it works quite well. I like having "custom" error-handling that fits the style and the purpose of that particular program, instead of trying to to fit a general pattern onto all programs. It also means you can start out with something very crude, and improve it as you go along and learn more about the failure modes etc.
- NateDad 12y agoThat's not really idiomatic. You should be adding context to the error you return, or a new error.
- lclarkmichalek 12y agoGiven its prevalence all across Go code, are you _sure_ it's not idiomatic? Hell, look at the presentation in the link: http://talks.golang.org/2014/readability.slide#11 http://talks.golang.org/2014/readability.slide#11. If the oracle of idioms does not write idiomatic code, then wtf is idiomatic code?
- NateDad 12y agoYou don't think people simplify some error handling to fit code on slides?
- mratzloff 12y ago> Go's error handling works well in small programs but there's a couple of issues. It works fine in big programs, too. If you need more context, you add custom errors that have a context field. If you need to match different types of errors, you can have an error code that you can check against, or you can simply match strings (a lot of Go code does this). What you see as a problem is not really much of a problem in practice for well-structured code.