by emmanueloga_ · 2y ago · 0 comments
Not an error handling improvement per-se, but if we had to sprinkle just one line of code instead of three around all spots of error handling, that would make me so much happier :-)
From:
if err != nil {
return err
}
To: return err if err != nil
... that is, allow ruby-style placing of conditionals after the return.https://github.com/golang/vscode-go/issues/2311
It papers over the issue, but helps some.
func x() (err error)
The short variable declaration syntax only requires that _at least one_ name is unique, so you can freely use the variable even in := sequences. So you end up with something like: if thing, err := impl(); err != nil {
return
} else {
// use thing
}
In the articles first example, the "problem" is that you have a core of a method that can return error or a widgetJSON. There should be a separate function that does precisely that. If you want to mash your http logic and your use logic into the same function, you're going to have a mess no matter how hard you try.The err in your if is a newly allocated variable by :=, different than the err allocated by the x prototype, and you’d also return a nil error even if impl returned an error.
The Go compiler is smart enough to prevent you from doing this beginner mistake:
result parameter err not in scope at return. inner declaration of var err error.
https://go.dev/play/p/VdWVOL51wZf
You would have to first declare thing prior to the if statement, then replace := by = .. the beauty of adding verbosity and longer-lived variables for the sake of trying to write return instead of return err in Go.
https://go.dev/play/p/qdjnH3JhzTN
Which does work because the rules on := are loose, but the if captured version creates a new scope that can't be shared with the return variable.
return err if thing, err := impl(); err != nil
// use thing
It would remove the indent, and plus you wouldn't need to name your return variable, that can sometimes be error prone (say, if you end up returning the wrong thing). Just a lil bit of sugar!I would not want to encounter that line of code in the wild, or 3 months after writing it, and attempt to parse what it's doing.
* in the wild, a LOT of code has the archetypical 3 lines: if err != nil { return err }, so I'm suggesting a lil sugar will remove this noise from countless lines of code across a lot of projects.
* If more processing is needed (ex: wrapping the error), use a function (return Wrap(err, ...), etc) or just revert to the normal if syntax.
if err != nil { return err }