Skip to content

Commit 3d0ae89

Browse files
Copilotcschleiden
authored andcommitted
Expose workflow.Cause to retrieve cancellation cause
1 parent 92ebb1a commit 3d0ae89

2 files changed

Lines changed: 31 additions & 0 deletions

File tree

workflow/context.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,16 @@ func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc) {
4343
return sync.WithCancelCause(parent)
4444
}
4545

46+
// Cause returns a non-nil error explaining why c was canceled.
47+
// The first cancellation of c or one of its parents sets the cause.
48+
// If that cancellation happened via a call to CancelCauseFunc(err),
49+
// then [Cause] returns err.
50+
// Otherwise Cause(c) returns the same value as c.Err().
51+
// Cause returns nil if c has not been canceled yet.
52+
func Cause(c Context) error {
53+
return sync.Cause(c)
54+
}
55+
4656
// WithValue returns a copy of parent in which the value associated with key is
4757
// val.
4858
//

workflow/context_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package workflow
2+
3+
import (
4+
"errors"
5+
"testing"
6+
7+
"github.com/cschleiden/go-workflows/internal/sync"
8+
"github.com/stretchr/testify/require"
9+
)
10+
11+
func TestCause(t *testing.T) {
12+
myErr := errors.New("my cause")
13+
14+
ctx, cancel := WithCancelCause(sync.Background())
15+
require.Nil(t, Cause(ctx))
16+
17+
cancel(myErr)
18+
19+
require.ErrorIs(t, ctx.Err(), Canceled)
20+
require.Equal(t, myErr, Cause(ctx))
21+
}

0 commit comments

Comments
 (0)