Skip to content

Instantly share code, notes, and snippets.

@lldld
Last active January 19, 2022 20:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lldld/bf93ca94c24f172e95baf8c123427ace to your computer and use it in GitHub Desktop.
Save lldld/bf93ca94c24f172e95baf8c123427ace to your computer and use it in GitHub Desktop.
go2 error handling feedback

Import symbol ! to passthrough errors

! is abbreviation of not nil

For example, to call function Sub in caller

func Sub(...) (T1, T2, error) {...}
  
func caller(...) (T3, error) {
	// call Sub(...)
}

Style 1 (same with go1)

	a, b, err := Sub(...)
	if err != nil {
		// do something
	}

Style 2 (!)

	a, b, ! := Sub(...)
		
	// Equivalent to
	a, b, err := Sub()
	if err != nil {
		return (default value of T3), err
	}

Style 3 (! func)

	a, b, !checkError := Sub(...)
	// Equivalent to
	a, b, err := Sub()
	! = checkError(err)
		
	!checkT1, b, !checkError := Sub(...)
	// Equivalent to
	a, b, err := Sub()
	! = checkError(err)
	! = checkT1(a)

Check funcs:

// prototype
func CheckReturn(r interface{}) error {...}
		
func checkError(err error) error {
	if err != nil {
		return errors.Wrap(err, "additional message")
	}
	return nil
}
		
func checkT1(a T1) error {
	if a.EqualTo(...) {
		return errors.Errorf("....")
	}
	return nil
}
		
@CannibalVox
Copy link

For whatever it's worth, I really like this one!

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