Skip to content

Instantly share code, notes, and snippets.

@podhmo
Created September 30, 2021 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save podhmo/6a71d16ca8b8f4ec63d65229faf9af41 to your computer and use it in GitHub Desktop.
Save podhmo/6a71d16ca8b8f4ec63d65229faf9af41 to your computer and use it in GitHub Desktop.
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