From c10df04cf1501b4c196ce6e02b3cddc04387ac1e Mon Sep 17 00:00:00 2001 From: lufia Date: Sun, 11 Jan 2026 11:27:11 +0900 Subject: [PATCH] add WithIgnore option --- try.go | 21 ++++++++++++++++++++- try_test.go | 8 ++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/try.go b/try.go index 812d7be..ce63d1d 100644 --- a/try.go +++ b/try.go @@ -1,7 +1,10 @@ // Package try provides error-handling utilities. package try -import "fmt" +import ( + "errors" + "fmt" +) // Checkpoint represents the fallback point. type Checkpoint struct { @@ -39,6 +42,19 @@ func WithDescription(format string, args ...any) Option { } } +func WithIgnore(errs ...error) Option { + return func(cp *Checkpoint) { + cp.handler = func(err error) error { + for _, e := range errs { + if errors.Is(err, e) { + return nil + } + } + return err + } + } +} + func waserror(cp *Checkpoint) bool func raise(cp *Checkpoint) bool func getbp(skip int) uintptr @@ -58,6 +74,9 @@ func (cp *Checkpoint) raise(skip int, err error) { } if cp.handler != nil { err = cp.handler(err) + if err == nil { + return + } } cp.err = err diff --git a/try_test.go b/try_test.go index 613096f..c1817d2 100644 --- a/try_test.go +++ b/try_test.go @@ -101,6 +101,14 @@ func TestCheck1_onErrorWithDescription(t *testing.T) { gt.String(t, msg).Equal("failed: fake") } +func TestCheck1_onErrorWithIgnore(t *testing.T) { + cp, err := Handle() + if err != nil { + t.Errorf("should ignore an error") + } + Check(fmt.Errorf("fake: %w", errors.ErrUnsupported))(cp, WithIgnore(errors.ErrUnsupported)) +} + func TestCheck2_onError(t *testing.T) { raised := false cp, err := Handle()