3 ms·
There's so much contention over error handling in Go. Over the years I've settled on treating it like gofmt: I may not 100% agree with all the choices, but it
by kcartlidge 3y ago
There's so much contention over error handling in Go. Over the years I've settled on treating it like gofmt: I may not 100% agree with all the choices, but it is what it is so let's just get on with it.
And to be honest as a majority-C# dev I quite like the break from exception handling.
As an aside, one thing I've found which makes life easier is to invert the check. With convoluted logic it can lead to excessive nesting, but then nobody would write code that did enough in a single function to make that an issue, surely?
Practical example. Here's what you might normally see:
err := doFunctionA()
if err != nil {
handleErrorFromFunctionA()
}
err = doFunctionB()
if err != nil {
handleErrorFromFunctionB()
}
err = doFunctionC()
if err != nil {
handleErrorFromFunctionC()
}
I'd usually just switch it:
err := doFunctionA()
if err == nil {
err = doFunctionB()
if err == nil {
err = doFunctionC()
}
}
if err != nil {
handleErrorRegardlessOfSource()
}
Of course it only works if the errors can be sensibly handled the same way regardless of their source, but that's surprisingly often the case (eg log, display, and/or return it).
It's just a minor change but it's standard uncomplicated Go, and with multiple sequential operations it reduces the code-waffle even more the larger the code gets.
YMMV and it isn't always suitable, but every little helps.