Simple `onErr` macro for common case error handling.

48 views
Skip to first unread message

Wojciech S. Czarnecki

unread,
Jul 4, 2019, 4:58:18 PM7/4/19
to golang-nuts
Robert Griesemer suggested[1] that `try` is just a macro. So I dare to propose a macro too,
based on an 'invisible semicolons' precedence and with a straightforward implementation.

## `onErr` simple macro for common case error handling. A #32437 counter-proposal.
To be read at https://github.com/golang/go/issues/32946. 40 lines, 173 words.


## Usage examples

```go

c, err := fn()
onErr continue

c, err := fn()
onErr {
x++
y = c
break
}

if c, err := fn(); onErr {
return x, y, c, err
}

```


## onErr macro

The `onErr` macro simplifies repeatable error handling, checking whether
`err` variable is not nil. Ie. the very `onErr` always is expanded to
mean `if err != nil`. The `err` identifier must be in the scope.

After an `onErr` either a block or five possible statements are allowed:
`continue`, `break`, `return`, `goto`, and a call to `panic(…)` built-in.

Then expansion occurs:

1. The `onErr` always is expanded to the `if err != nil` statement.
2. If there is a block after `onErr`, the expansion ends.
3. If there is an allowed statement, it acts as given in an implicit curly braces.



[1] https://github.com/golang/go/issues/32611#issuecomment-508302256


Enjoy!

--
Wojciech S. Czarnecki
<< ^oo^ >> OHIR-RIPE
Reply all
Reply to author
Forward
0 new messages