I'm considering learning go but amount of 'return err' and 'return nil, 0, err' is instant turn-off. Is this best-practice error handling in go ? Thanks !
I'm considering learning go but amount of 'return err' and 'return nil, 0, err' is instant turn-off. Is this best-practice error handling in go ? Thanks !
The only think that could be done better is instead of always blindly returning an error, one could wrap them in higher level errors and build a sort of error trace:
E.g:
- task failed because
- authentication failed because
- could not load credentials because
- because file xy.pem is not readable
But instead of the above, you often just receive a "permission error", but you don't know where it came from, which can make debugging hard.Edit: formatting
>instead of always blindly returning an error, one could wrap them in higher level errors and build a sort of error trace
Isn't that basically just reinventing exceptions, sort-of ?
Exceptions only contain a function call trace (stack of function calls), while a logical error trace is more like an explicit try/catch/wrap/throw around every call and could be more informative to the end user if done properly.
If you want to write it safely, you will have `if err != nil` everywhere.
This is normal and expected.
The best phrasing I've heard recently is "Go is useful drudgery".
For example, BuildStats is defined as returning (* stats, int, error), when it could name those and just use naked returns. In buildInstancesStats, they name the return values but then repeat them again on all 3 return lines instead of just using a naked "return".
Quick intro form the tour with a good example: https://tour.golang.org/basics/7