Skip to content

Commit

Permalink
Add ErrContext method to Result
Browse files Browse the repository at this point in the history
  • Loading branch information
knpwrs committed Aug 17, 2024
1 parent 6745eff commit c0c153f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
8 changes: 8 additions & 0 deletions result.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,14 @@ func (r Result[T]) MapErr(mapper func(error) (T, error)) Result[T] {
return Ok(r.value)
}

func (r Result[T]) ErrContext(context string) Result[T] {
if r.isErr {
return Err[T](fmt.Errorf("%s\n\nOriginal Error:\n%s", context, r.err.Error()))
}

return Ok(r.value)
}

// FlatMap executes the mapper function if Result is valid. It returns a new Result.
// Play: https://go.dev/play/p/Ud5QjZOqg-7
func (r Result[T]) FlatMap(mapper func(value T) Result[T]) Result[T] {
Expand Down
8 changes: 8 additions & 0 deletions result_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,14 @@ func TestResultMapErr(t *testing.T) {
is.Equal(Result[int]{value: 42, isErr: false, err: nil}, opt2)
}

func TestResultErrContext(t *testing.T) {
is := assert.New(t)

opt := Err[int](assert.AnError).ErrContext("Oh bananas")

is.Equal(Result[int]{value: 0, isErr: true, err: errors.New("Oh bananas\n\nOriginal Error:\nassert.AnError general error for testing")}, opt)
}

func TestResultFlatMap(t *testing.T) {
is := assert.New(t)

Expand Down

0 comments on commit c0c153f

Please sign in to comment.