Created
June 26, 2018 08:40
-
-
Save roylee0704/178eb3fe5296dddb73ab760e6996b890 to your computer and use it in GitHub Desktop.
pkg/error cause 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
It walks the stack-trace from
pkg/error
to see if it exhibits certain behavior for special handling.