Explaining Go error handling
Ivan Danyliuk

That is all good and all, but I find that what people really find annoying is repetitive error handling when you can only fail to the caller telling how far you got on a linear sequence of steps. This is very typical when writing code that does IO or system calls, and each can fail with an error:

  1. Do step one (maybe open file)
  2. Do step 2 (maybe configure)
  3. Do step 3 (maybe a write loop, where you can use the code in the article)
  4. Do step 4 (maybe close)

As all steps are different, making a similar approach to the above for all 4 cases is an overkill.

Instead you end up doing the 3 liner “if step x fails return err”

The only alternative I see is to nest all succesful steps on ifs and have a single outside return for the error:

if ok = step1(); ok {

if step2(); ok {

if step3(); ok {

… return ok, nil




return nil, err

But this also turns ugly if you have many steps, as you end up with too many nested ifs.

Any alternatives?

(Yep, it is true you sometimes might need to do something else more than returning the err, in which checking the error with an enclosing if and some different code is justified)

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.