Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion try.go
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -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

Expand Down
8 changes: 8 additions & 0 deletions try_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down