|
|
|
|
|
by 9rx
447 days ago
|
|
You may as well use exception handlers if you're going to go there. func foo() (final int, err error) {
defer func() {
if e, ok := recover().(failure); ok {
err = e
} else {
panic(e)
}
}()
first := getFirst()
doWith(first)
final = doFinally()
return
}
encoding/json does it. It's okay if you understand the tradeoffs.But look at what you could have wrote: func foo() (int, error) {
first, err := getFirst()
if err != nil {
return 0, ErrFirst
}
err = doWith(first)
if err != nil {
return 0, ErrDo
}
final, err := doFinally()
if err != nil {
return 0, ErrFinally
}
return final, nil
}
This one is actually quite nice to read, unlike the others, and provides a better experience for the caller too – which is arguably more important than all other attributes. |
|
I think something similar to the second one is also nice to read, and it gives the same improved experience to the caller as your suggestion.