Skip to content

Commit

Permalink
Merge pull request #19 from ccremer/errorhandler
Browse files Browse the repository at this point in the history
Add error handler
  • Loading branch information
ccremer authored Dec 20, 2021
2 parents 789f52b + 5767ea6 commit f061a18
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
12 changes: 12 additions & 0 deletions step.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,15 @@ func (s Step) WithResultHandler(handler ResultHandler) Step {
s.H = handler
return s
}

// WithErrorHandler wraps given errorHandler and sets the ResultHandler of this specific step and returns the step itself.
// The difference to WithResultHandler is that errorHandler only gets called if Result.Err is non-nil.
func (s Step) WithErrorHandler(errorHandler func(ctx Context, err error) error) Step {
s.H = func(ctx Context, result Result) error {
if result.IsFailed() {
return errorHandler(ctx, result.Err)
}
return nil
}
return s
}
38 changes: 38 additions & 0 deletions step_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package pipeline

import (
"errors"
"testing"

"github.com/stretchr/testify/assert"
)

func TestStep_WithErrorHandler(t *testing.T) {
tests := map[string]struct {
givenError error
expectedExecution bool
}{
"GivenHandler_WhenErrorIsNil_ThenDoNotRunHandler": {
givenError: nil,
expectedExecution: false,
},
"GivenHandler_WhenErrorGiven_ThenExecuteHandler": {
givenError: errors.New("error"),
expectedExecution: true,
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
executed := false
s := NewStepFromFunc("test", func(_ Context) error {
return nil
}).WithErrorHandler(func(_ Context, err error) error {
executed = true
return err
})
err := s.H(nil, Result{Err: tt.givenError})
assert.Equal(t, tt.givenError, err)
assert.Equal(t, tt.expectedExecution, executed)
})
}
}

0 comments on commit f061a18

Please sign in to comment.