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
49 changes: 38 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
```
Expand Down Expand Up @@ -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))
...
}
```
Expand All @@ -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
```
4 changes: 2 additions & 2 deletions example_opts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
63 changes: 63 additions & 0 deletions go127.go
Original file line number Diff line number Diff line change
@@ -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
}
}
34 changes: 34 additions & 0 deletions go127_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
104 changes: 59 additions & 45 deletions try.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,55 +10,65 @@ import (
// Checkpoint represents the fallback point.
type Checkpoint[E error] struct {
regs
err E
handlers []func(err E) E
err E
}

type regs struct {
sp uintptr
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
})
}
}

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
Expand All @@ -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
Expand All @@ -118,38 +114,55 @@ 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)
}
}

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
}
}
Expand All @@ -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
}
}
Loading