Created
September 30, 2021 06:07
-
-
Save podhmo/6a71d16ca8b8f4ec63d65229faf9af41 to your computer and use it in GitHub Desktop.
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
package main | |
import ( | |
"errors" | |
"fmt" | |
"log" | |
pkgerrors "github.com/pkg/errors" | |
) | |
type FooError struct { | |
Msg string | |
} | |
func (e *FooError) Error() string { | |
return fmt.Sprintf("FOOO %s", e.Msg) | |
} | |
func main() { | |
if err := run(); err != nil { | |
log.Fatalf("!! %+v", err) | |
} | |
} | |
func run() error { | |
var fooErr *FooError | |
fmt.Println("foo as Foo?", errors.As(foo(), &fooErr)) // true | |
fmt.Println("withWrap-foo as Foo?", errors.As(withWrap(), &fooErr)) // true | |
fmt.Println("withWrap-foo cause Foo?", ok(withWrap())) // true | |
fmt.Println("errorf-foo as Foo?", errors.As(withErrorf(), &fooErr)) // true | |
fmt.Println("errorf-foo cause Foo?", ok(withErrorf())) // false | |
return nil | |
} | |
func ok(err error) bool { | |
_, ok := pkgerrors.Cause(err).(*FooError) | |
return ok | |
} | |
func foo() error { | |
return &FooError{Msg: "hmm"} | |
} | |
func withWrap() error { | |
if err := foo(); err != nil { | |
return pkgerrors.Wrap(err, "with pkg.errors.Wrap") | |
} | |
return nil | |
} | |
func withErrorf() error { | |
if err := foo(); err != nil { | |
return fmt.Errorf("with errorf: %w", err) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment