diff --git a/README.md b/README.md index 2b95702..14e4b9d 100644 --- a/README.md +++ b/README.md @@ -37,8 +37,13 @@ func Run(file string) (string, error) { if err != nil { return "", err } + s := cp.Check1(os.ReadFile(file)) + u := cp.Check1(url.Parse(string(s))) + + // If you use Go 1.26 or earlier, use function style instead. s := try.Check1(os.ReadFile(file))(cp) u := try.Check1(url.Parse(string(s)))(cp) + return u.Path, nil } ``` @@ -81,22 +86,36 @@ func GetAlerts(w http.ResponseWriter, r *http.Request) { The example above can rewrite more simple with **try**. ```go +type httpError struct { + Err error + Code int +} + +func (e *httpError) Error() string { return e.Err.Error() } + +func (e *httpError) Unwrap() error { return e.Err } + +func e(err error, code int) *httpError { + if err == nil { return nil } + return &httpError{err, code} +} + func GetAlerts(w http.ResponseWriter, r *http.Request) { - on400, err := try.Handle() - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - on500, err := try.Handle() + cp, err := try.HandleFor[*httpError]() if err != nil { - http.Error(w, err.Error(), http.InternalServerError) + http.Error(w, http.StatusText(err.Code), err.Code) return } + cp.Check(e(r.ParseForm(), http.StatusBadRequest)) + + orgID, err := strconv.Atoi(r.Form.Get("orgId")) + cp.Check(e(err, http.StatusBadRequest)) + + alerts, err := repository.FetchAlerts(orgID) + cp.Check(e(err, http.StatusInternalServerError)) - try.Check(r.ParseForm())(on400) - orgID := try.Check1(strconv.Atoi(r.Form.Get("orgId")))(on400) - alerts := try.Check1(repository.FetchAlerts(orgID))(on500) - body := try.Check1(json.Marshal(alerts))(on500) + body, err := json.Marshal(alerts) + cp.Check(e(err, http.StatusInternalServerError)) ... } ``` @@ -111,6 +130,14 @@ if err != nil { return nil, err } buf := make([]byte, 1<<8) + +n := cp.Check1Options(os.Stdin.Read(buf))( + try.WithIgnore(io.EOF), + try.WithDescription("failed to read"), +) + +// If you use Go 1.26 or earlier, use function style instead. n := try.Check1(os.Stdin.Read(buf))(cp, try.WithIgnore(io.EOF), try.WithDescription("failed to read")) + return buf[:n], nil ``` diff --git a/example_opts_test.go b/example_opts_test.go index af952e3..de4c479 100644 --- a/example_opts_test.go +++ b/example_opts_test.go @@ -8,12 +8,12 @@ import ( ) func ExampleCheck1_withOptions() { - s, err := try.Handle() + cp, err := try.Handle() if err != nil { fmt.Println(err) return } - v := try.Check1(os.ReadFile("NOFILE"))(s, try.WithDescription("failed to read a file")) + v := try.Check1(os.ReadFile("NOFILE"))(cp, try.WithDescription("failed to read a file")) fmt.Println("value:", v) // Output: // failed to read a file: open NOFILE: no such file or directory diff --git a/example_test.go b/example_test.go index d2cf869..4ccd996 100644 --- a/example_test.go +++ b/example_test.go @@ -8,12 +8,12 @@ import ( ) func Example() { - s, err := try.Handle() + cp, err := try.Handle() if err != nil { fmt.Println("error:", err) return } - v := try.Check1(read())(s) + v := try.Check1(read())(cp) fmt.Println("value:", v) // Output: // error: unsupported operation diff --git a/go127.go b/go127.go new file mode 100644 index 0000000..20b969c --- /dev/null +++ b/go127.go @@ -0,0 +1,63 @@ +//go:build go1.27 + +package try + +// Check checks whether err is not nil. +// If err is nil, it does nothing. +// Otherwise it rewinds to the fallback point cp, then [Handle] or [HandleFor] returns err. +// +// Check should be called on the same stack to [Handle] or [HandleFor]. +func (cp *Checkpoint[E]) Check(err E) { + var o options[E] + cp.raise(1, err, &o) +} + +// Check1 checks whether err is not nil. +// If err is nil, it returns v. +// Otherwise it rewinds to the fallback point cp, then [Handle] or [HandleFor] returns err. +// +// Check1 should be called on the same stack to [Handle] or [HandleFor]. +func (cp *Checkpoint[E]) Check1[T any](v T, err E) T { + var o options[E] + cp.raise(1, err, &o) + return v +} + +// Check2 is a variant of [Checkpoint.Check1]. +func (cp *Checkpoint[E]) Check2[T1, T2 any](v1 T1, v2 T2, err E) (T1, T2) { + var o options[E] + cp.raise(1, err, &o) + return v1, v2 +} + +// CheckOptions is a variant of [Checkpoint.Check]. +// It returns a function that accepts options. +func (cp *Checkpoint[E]) CheckOptions(err E) func(opts ...Option[E]) { + return func(opts ...Option[E]) { + var o options[E] + applyOpts(&o, opts...) + cp.raise(1, err, &o) + } +} + +// Check1Options is a variant of [Checkpoint.Check1]. +// It returns a function that accepts options. +func (cp *Checkpoint[E]) Check1Options[T any](v T, err E) func(opts ...Option[E]) T { + return func(opts ...Option[E]) T { + var o options[E] + applyOpts(&o, opts...) + cp.raise(1, err, &o) + return v + } +} + +// Check2Options is a variant of [Checkpoint.Check2]. +// It returns a function that accepts options. +func (cp *Checkpoint[E]) Check2Options[T1, T2 any](v1 T1, v2 T2, err E) func(opts ...Option[E]) (T1, T2) { + return func(opts ...Option[E]) (T1, T2) { + var o options[E] + applyOpts(&o, opts...) + cp.raise(1, err, &o) + return v1, v2 + } +} diff --git a/go127_test.go b/go127_test.go new file mode 100644 index 0000000..00829d4 --- /dev/null +++ b/go127_test.go @@ -0,0 +1,34 @@ +//go:build go1.27 + +package try + +import ( + "errors" + "testing" + + "github.com/m-mizutani/gt" +) + +func TestCheckpoint_Check(t *testing.T) { + msg := "" + cp, err := Handle() + if err != nil { + msg = err.Error() + } + if msg == "" { + cp.Check(errors.New("fake")) + } + gt.String(t, msg).Equal("fake") +} + +func TestCheckpoint_CheckOptions(t *testing.T) { + msg := "" + cp, err := Handle() + if err != nil { + msg = err.Error() + } + if msg == "" { + cp.CheckOptions(errors.New("fake"))(WithDescription("failed")) + } + gt.String(t, msg).Equal("failed: fake") +} diff --git a/try.go b/try.go index 84f52d7..6a2d61a 100644 --- a/try.go +++ b/try.go @@ -10,8 +10,7 @@ import ( // Checkpoint represents the fallback point. type Checkpoint[E error] struct { regs - err E - handlers []func(err E) E + err E } type regs struct { @@ -19,39 +18,44 @@ type regs struct { bp uintptr ctxt uintptr pc uintptr - probe uintptr // BP of Handle's parent + probe uintptr // checks whether stack had been moved or not. } -// Option configures [Check], [Check1] and [Check2]. -type Option[E error] func(*Checkpoint[E]) - -func applyOpts[E error](cp *Checkpoint[E], opts ...Option[E]) { - for _, opt := range opts { - opt(cp) - } +type options[E error] struct { + handlers []func(err E) E } +// Option configures [Check], [Check1] and [Check2]. +type Option[E error] func(*options[E]) + +// WithHandler returns an option for a [Checkpoint] with f. +// +// When [Check] or its variants are called, f is invoked with the error if it is non-nil. +// Additionally, if f returns a zero value, [Check] or its variants do not treat it as an error. func WithHandler[E error](f func(err E) E) Option[E] { - return func(cp *Checkpoint[E]) { - cp.handlers = append(cp.handlers, f) + return func(o *options[E]) { + o.handlers = append(o.handlers, f) } } +// WithDescription returns an option for a [Checkpoint] with [fmt.Printf]-style arguments. func WithDescription(format string, args ...any) Option[error] { prefix := fmt.Sprintf(format, args...) - return func(cp *Checkpoint[error]) { - cp.handlers = append(cp.handlers, func(err error) error { + return func(o *options[error]) { + o.handlers = append(o.handlers, func(err error) error { return fmt.Errorf("%s: %w", prefix, err) }) } } -func WithIgnore(errs ...error) Option[error] { - return func(cp *Checkpoint[error]) { - cp.handlers = append(cp.handlers, func(err error) error { +// WithIgnore returns an option for a [Checkpoint] to ignore errors. +func WithIgnore[E error](errs ...E) Option[E] { + return func(o *options[E]) { + o.handlers = append(o.handlers, func(err E) E { for _, e := range errs { if errors.Is(err, e) { - return nil + var zero E + return zero } } return err @@ -59,6 +63,12 @@ func WithIgnore(errs ...error) Option[error] { } } +func applyOpts[E error](o *options[E], opts ...Option[E]) { + for _, opt := range opts { + opt(o) + } +} + func waserror(cp uintptr) bool func raise(cp uintptr) bool func stkhi() uintptr @@ -82,25 +92,11 @@ func HandleFor[E error]() (*Checkpoint[E], E) { return &cp, zero } -func isZero[T any](v T) bool { - n := unsafe.Sizeof(v) - if n == 0 { - return true - } - b := unsafe.Slice((*byte)(unsafe.Pointer(&v)), n) - for _, n := range b { - if n != 0 { - return false - } - } - return true -} - -func (cp *Checkpoint[E]) raise(skip int, err E) { +func (cp *Checkpoint[E]) raise(skip int, err E, o *options[E]) { if isZero(err) { return } - for _, f := range cp.handlers { + for _, f := range o.handlers { err = f(err) if isZero(err) { return @@ -118,24 +114,40 @@ func (cp *Checkpoint[E]) raise(skip int, err E) { panic("do not reach here") } +func isZero[T any](v T) bool { + n := unsafe.Sizeof(v) + if n == 0 { + return true + } + b := unsafe.Slice((*byte)(unsafe.Pointer(&v)), n) + for _, n := range b { + if n != 0 { + return false + } + } + return true +} + // Rewind rewinds current execution point to cp. // // Deprecated: use goto statement instead. func (cp *Checkpoint[E]) Rewind(err E) { - cp.raise(1, err) + var o options[E] + cp.raise(1, err, &o) } type RewinderFunc[E error] func(*Checkpoint[E], ...Option[E]) // Check checks whether err is not nil. // If err is nil, it does nothing. -// Otherwise it rewinds to the fallback point s, then [Handle] returns err. +// Otherwise it rewinds to the fallback point cp, then [Handle] or [HandleFor] returns err. // -// Check should be called on the same stack to [Handle]. +// Check should be called on the same stack to [Handle] or [HandleFor]. func Check[E error](err E) RewinderFunc[E] { return func(cp *Checkpoint[E], opts ...Option[E]) { - applyOpts(cp, opts...) - cp.raise(1, err) + var o options[E] + applyOpts(&o, opts...) + cp.raise(1, err, &o) } } @@ -143,13 +155,14 @@ type RewinderFunc1[T any, E error] func(*Checkpoint[E], ...Option[E]) T // Check1 checks whether err is not nil. // If err is nil, it returns v. -// Otherwise it rewinds to the fallback point s, then [Handle] returns err. +// Otherwise it rewinds to the fallback point cp, then [Handle] or [HandleFor] returns err. // -// Check1 should be called on the same stack to [Handle]. +// Check1 should be called on the same stack to [Handle] or [HandleFor]. func Check1[T any, E error](v T, err E) RewinderFunc1[T, E] { return func(cp *Checkpoint[E], opts ...Option[E]) T { - applyOpts(cp, opts...) - cp.raise(1, err) + var o options[E] + applyOpts(&o, opts...) + cp.raise(1, err, &o) return v } } @@ -159,8 +172,9 @@ type RewinderFunc2[T1, T2 any, E error] func(*Checkpoint[E], ...Option[E]) (T1, // Check2 is a variant of [Check1]. func Check2[T1, T2 any, E error](v1 T1, v2 T2, err E) RewinderFunc2[T1, T2, E] { return func(cp *Checkpoint[E], opts ...Option[E]) (T1, T2) { - applyOpts(cp, opts...) - cp.raise(1, err) + var o options[E] + applyOpts(&o, opts...) + cp.raise(1, err, &o) return v1, v2 } }