Skip to content

Instantly share code, notes, and snippets.

@markbates
Last active June 29, 2019 08:22
Show Gist options
  • Save markbates/12083cbb1e58d56bfb037be8f6cec2cc to your computer and use it in GitHub Desktop.
Save markbates/12083cbb1e58d56bfb037be8f6cec2cc to your computer and use it in GitHub Desktop.
Unwrap Go errors from the go 2 errors proposal as well as github.com/pkg/errors
package foo
// go2 errors
type wrapper interface {
Unwrap() error
}
// pkg/errors
type causer interface {
Cause() error
}
func unwrap(err error) error {
switch e := err.(type) {
case wrapper:
return e.Unwrap()
case causer:
return e.Cause()
}
return err
}
@cristaloleg
Copy link

Last return in unwrap can be under default statement inside the switch :)

func unwrap(err error) error {
	switch e := err.(type) {
	case wrapper:
		return e.Unwrap()
	case causer:
		return e.Cause()
	default:
		return err
	}
}

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