Skip to content

Commit

Permalink
feat: handle panic with stack
Browse files Browse the repository at this point in the history
  • Loading branch information
areknoster authored and peterlgh7 committed Apr 20, 2023
1 parent e35bd53 commit 13fe584
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
3 changes: 2 additions & 1 deletion node.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package jpipe

import (
"fmt"
"runtime/debug"
"sync"

"github.com/junitechnology/jpipe/options"
Expand Down Expand Up @@ -170,7 +171,7 @@ func (node *node[T, R]) LoopInput(i int, function func(value T) bool) {

func (node *node[T, R]) HandlePanic() {
if r := recover(); r != nil {
node.pipeline.Cancel(fmt.Errorf("%v", r))
node.pipeline.Cancel(fmt.Errorf("%v: %s", r, debug.Stack()))
}
}

Expand Down
19 changes: 19 additions & 0 deletions pipeline_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,22 @@ func TestPipelineDoneWhenContextDone(t *testing.T) {
assert.True(t, pipeline.IsDone())
assert.ErrorIs(t, pipeline.Error(), context.Canceled)
}

func TestPipelineRecoversFromPanicAndIncludesStacktrace(t *testing.T) {
pipeline := jpipe.NewPipeline(jpipe.Config{})
jpipe.
FromSlice(pipeline, []int{1, 2, 3}).
ForEach(func(value int) {
panic("panic")
})

select {
case <-pipeline.Done():
case <-time.After(time.Millisecond):
assert.Fail(t, "Pipeline must be done if context is canceled")
}
assert.True(t, pipeline.IsDone())
t.Logf("panic error:\n %v", pipeline.Error().Error())
assert.Contains(t, pipeline.Error().Error(), "panic")
assert.Contains(t, pipeline.Error().Error(), "TestPipelineRecoversFromPanicAndIncludesStacktrace") // this shows that the stacktrace is included
}

0 comments on commit 13fe584

Please sign in to comment.