Skip to content

internal: ensure errors.Append has an error

Administrator requested to merge devx/lib-errors-append-proposal into main

Created by: jhchabran

While I was writing some code appending errors, I accidentally wrote:

var errs error 
for _, elem := range things {
  err := doSomething(elem)
  errs = errors.Append(err) 
}

Can you spot the mistake? It should have been

  errs = errors.Append(errs, err) 

It's very similar to using append correctly, but somehow, because the package name is errors my brain did not register the mistake, as it looked like I was calling Append on a struct named errors.

It's obvious that I'm the one at fault here, but keeping in mind the fact that often don't look at errors as much as we look at the slice we're appending to, it's much easier to miss this one, such a mistake could go unnoticed for a long time. At least, I would have in the present case if I did have written a unit test to ensure I was accumulating the errors.

An easy fix is to declare it as:

func Append(err error, firstErr error, errs ...error) MultiError

The only issue is that it prevents things like errors.Append(errs, others...).

💡 Maybe that should be a linter actually!

Test plan

The whole codebase builds and tests are green.

Merge request reports

Loading