Created
June 26, 2018 08:39
-
-
Save roylee0704/39e592a17ce25755cad73f5ea4022382 to your computer and use it in GitHub Desktop.
pkg/error inspector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type errTwo struct{} | |
func (errTwo) Error() string { | |
return "errTwo" | |
} | |
type errOne struct{} | |
func (errOne) Error() string { | |
return "errOne" | |
} | |
func (errOne) BadArguments() string { | |
return "bad bad arguments" | |
} | |
func (errOne) Behave() { | |
} | |
func main() { | |
errOne := errors.Wrap(errOne{}, "first error message") | |
errTwo := errors.Wrap(errOne, "second error message") | |
errThree := errors.Wrap(errTwo, "third error message") | |
fmt.Println(inspectCause(errThree, func(err error) (ok bool) { | |
_, ok = err.(behaver) | |
return | |
})) | |
} | |
type behaver interface { | |
Behave() | |
} | |
func inspectCause(err error, inspect func(err error) bool) bool { | |
type causer interface { | |
Cause() error | |
} | |
var hasBehavior bool | |
for err != nil { | |
hasBehavior = inspect(err) | |
cause, ok := err.(causer) | |
if !ok { | |
break | |
} | |
err = cause.Cause() | |
} | |
return hasBehavior | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment