Error Handling in Go 2

257 views
Skip to first unread message

Kaveh Shahbazian

unread,
Jul 29, 2020, 10:46:17 AM7/29/20
to golang-nuts
Go can already pass/pipe the result of a function, which returns multiple values, to another function, which accepts the same values as arguments. A similar mechanism can be used for handling errors, by passing/pipe them to a special construct.

Now, assume we have a function named funcCtx:

func funcCtx() (res int, err error) {
    // ...
}


Having that, these does not look that ugly:

func funcCtx() (res int, err error) {
    res, return() = action()
    // or
    res, panic() = action()
}


Those statements will have an effect, only if the returned value is not nil. For performing some actions, before the actual return or panic:

res, return({ log.Println(err) }) = action()

There is this restriction, that the function that contains this block, funcCtx, has to return named return values - for both handling the zero values and having a one to one mapping between its return values and those of action function.

Also for having a name, err in this case, that makes it clear, which variable we are talking about.

In the proposal, it's not clear where the err variable comes from (what if there are three return values?)

Ian Lance Taylor

unread,
Jul 29, 2020, 11:46:39 PM7/29/20
to Kaveh Shahbazian, golang-nuts
Thanks. This idea seems somewhat similar to https://golang.org/issue/27519.

Ian

Kaveh Shahbazian

unread,
Jul 30, 2020, 3:56:39 PM7/30/20
to golang-nuts
In that proposal, some more syntax and semantics are being added - IMHO.

One problem here is the name of the error variable. Here we explicitly have to used named return values - no new syntax there.

And return() and panic() on left side, only accept error type.
They will only be triggered when the error is not nil.

The concept is similar to piping functions - which Go already has a nice form of it.

This approach is far more restricted and removes only the if someError != nil part. So there is much less room for "creativity".

It enforces following early return technique/pattern. Which leads to more clear code.

For anything more complicated (in terms of conditions for handling the error), we have to write the more complicated solution.
Reply all
Reply to author
Forward
0 new messages