go 16 lines · 1 tab

errors.Join for cleanup (surface multiple close failures)

Leah Thompson Jan 2026
1 tab
package cleanup

import "errors"

func CloseAll(closers ...func() error) error {
  var errs []error
  for _, c := range closers {
    if c == nil {
      continue
    }
    if err := c(); err != nil {
      errs = append(errs, err)
    }
  }
  return errors.Join(errs...)
}
1 file · go Explain with highlit

Cleanup paths are easy to under-test, and it’s common to ignore close errors because you only have one return value. With Go 1.20+, errors.Join gives you a clean way to accumulate multiple cleanup errors and return them as a single error value. This is especially useful when you have several resources to close (rows, files, temp dirs) and you don’t want the first failure to hide the second. In production, this matters for batch jobs and import pipelines where a failed flush or close can mean data loss. The helper below takes a list of func() error closers and joins any errors it sees. It stays readable and keeps cleanup logic centralized. Combine this with structured logs and you’ll actually notice close failures instead of silently discarding them.


Related snips

Share this code

Here's the card — post it anywhere.

errors.Join for cleanup (surface multiple close failures) — share card
Link copied