Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a decorator for callback error handling #100

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
34 changes: 34 additions & 0 deletions event_decorators.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package fsm

import "context"

// CallbackWithErr is an FSM callback function that can return an error. The primary use case for this is for
// CallbackWithErr to be used as an argument to DecorateCallbackWithErrorHandling.
type CallbackWithErr func(ctx context.Context, event *Event) error

// DecorateCallbackWithErrorHandling is a decorator for FSM callbacks that will catch any errors returned by the
// callback and set them on the event's Err field. This is useful for standardizing the way any error encountered
// during an FSM callback are handled.
// Example usage:
//
// fsm := NewFSM(
// "start",
// Events{
// {Name: "run", Src: []string{"start"}, Dst: "end"},
// },
// Callbacks{
// "before_event": DecorateCallbackWithErrorHandling(
// func(_ context.Context, e *Event) error {
// return errors.New("testing error handling decorator")
// },
// ),
// },
// )
func DecorateCallbackWithErrorHandling(callback CallbackWithErr) Callback {
return func(ctx context.Context, event *Event) {
err := callback(ctx, event)
if err != nil {
event.Err = err
}
}
}
33 changes: 33 additions & 0 deletions event_decorators_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package fsm

import (
"context"
"errors"
"testing"
)

func TestDecorateCallbackWithErrorHandling(t *testing.T) {
t.Parallel()

fsm := NewFSM(
"start",
Events{
{Name: "run", Src: []string{"start"}, Dst: "end"},
},
Callbacks{
"before_event": DecorateCallbackWithErrorHandling(
func(_ context.Context, e *Event) error {
return errors.New("testing error handling decorator")
},
),
},
)

err := fsm.Event(context.Background(), "run")
if err == nil {
t.Error("expected error to be returned from event")
}
if err.Error() != "testing error handling decorator" {
t.Errorf("expected error to be 'testing error handling decorator', got '%s'", err.Error())
}
}
Loading