In this case the error from cleanup is ignored. Not good.

func action() error {
	  return errors.New("failed to perform action")
}

func cleanup() error {
		return errors.New("failed to cleanup")
}

func DoAction() error {
		defer cleanup()
		return action()
}

To properly process the error AND not overwrite the original error:

  1. Use named return arguments
  2. Use errors.Join to process both errors
func DoAction() (err error) {
		defer func() {
				err = errors.Join(err, cleanup())
		}()
		return action()
}

Links