The return of the return

Error Handling for Go 2

Martin Rode
2 min readNov 30, 2018

This story describes a somewhat radical idea to improve error management in Go.

Following the discussion about how to do error management right in Go 2.0, I am somewhat unhappy and unsatisfied with all the ideas I’ve read about so far.

Take the example from the Go2 Error Handling Proposal (non cheating version):

func CopyFile(src, dst string) error {
r, err := os.Open(src)
if err != nil {
return fmt.Errorf("copy %s %s: %v", src, dst, err)
}
defer r.Close()
w, err := os.Create(dst)
if err != nil {
return fmt.Errorf("copy %s %s: %v", src, dst, err)
}
_, err := io.Copy(w, r)
if err != nil {
w.Close()
os.Remove(dst)
return fmt.Errorf("copy %s %s: %v", src, dst, err)
}
err := w.Close()
if err != nil {
os.Remove(dst)
return fmt.Errorf("copy %s %s: %v", src, dst, err)
}
}

Boring, right?

So, how about we introduce a new way of returning from a function, the return2x. The return2x would not only return from the function we call it from, but also from the function the caller is in. mayreturn is required when calling a function which uses return2x.

The above code could be rewritten as:

func CopyFile(src, dst string) error {
check := func(err) {
if err != nil {
return2x fmt.Errorf("copy %s %s: %v", src, dst, err)
}
}
r, err := os.Open(src)
mayreturn check(err)
defer r.Close()
w, err := os.Create(dst)
mayreturn check(err)
_, err := io.Copy(w, r)
if err != nil {
defer func()
w.Close()
os.Remove(dst)
mayreturn check(err)
}
err := w.Close()
if err != nil {
os.Remove(dst)
mayreturn check(err)
}
}

You like? I would be very happy about this and I could improve my error handling a lot all over the place!

return2x would need to match the same return values as required for the outer function.

mayreturn is needed to allow a function to use return2x.

I think that return2x is more the Go like way to keep things simple.

I share most critical points from Liam Breck’s article, tdea to use check & handler is introducing unnecessary complexity without much gain!

So, how about the return of the return?

I am looking forward to your comments.

--

--