Skip to content

Instantly share code, notes, and snippets.

@elimisteve
Last active September 8, 2018 22:20
Show Gist options
  • Save elimisteve/e1afa0f936e549986a6021b841331144 to your computer and use it in GitHub Desktop.
Save elimisteve/e1afa0f936e549986a6021b841331144 to your computer and use it in GitHub Desktop.
Go 2 error handling

Based on what I believe to be the best ideas proposed for Go 2 -- namely https://gist.github.com/akavel/62d90bdc43088574c638eb3b16301a92#gistcomment-2692584 -- here is what a key example from the Go 2 error handling proposal would look like:

This example from https://go.googlesource.com/proposal/+/master/design/go2draft-error-handling-overview.md

func CopyFile(src, dst string) error {
	handle err {
		return fmt.Errorf("copy %s %s: %v", src, dst, err)
	}

	r := check os.Open(src)
	defer r.Close()

	w := check os.Create(dst)
	handle err {
		w.Close()
		os.Remove(dst) // (only if a check fails)
	}

	check io.Copy(w, r)
	check w.Close()
	return nil
}

should become

func CopyFile(src, dst string) error {
	handle err {
		return fmt.Errorf("copy %s %s: %v", src, dst, err)
	}

	r := check os.Open(src)
	defer r.Close()

	w := check os.Create(dst)

	defer func() {
		if err != nil {
			w.Close()
			os.Remove(dst) // (only if a check fails)
		}
	}()

	check io.Copy(w, r)
	check w.Close()
	return nil
}

I agree with the counter-proposals insisting that each handle block should return; without this, error handling becomes scattered all over the place and we thus lose the localized error handling characterized by Go contra languages that use exceptions, which we should continue not to emulate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment