Skip to content

Commit

Permalink
chore: log panic line in ticker error (#2881)
Browse files Browse the repository at this point in the history
  • Loading branch information
gartnera authored Sep 16, 2024
1 parent 2c87c5c commit 77cf636
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
11 changes: 10 additions & 1 deletion pkg/ticker/ticker.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ package ticker
import (
"context"
"fmt"
"runtime/debug"
"strings"
"sync"
"time"

Expand Down Expand Up @@ -78,7 +80,14 @@ func SecondsFromUint64(d uint64) time.Duration {
func (t *Ticker) Run(ctx context.Context) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic during ticker run: %v", r)
stack := string(debug.Stack())
lines := strings.Split(stack, "\n")
line := ""
// 8th line should be the actual line, see the unit tests
if len(lines) > 8 {
line = strings.TrimSpace(lines[8])
}
err = fmt.Errorf("panic during ticker run: %v at %s", r, line)
}
}()

Expand Down
27 changes: 27 additions & 0 deletions pkg/ticker/ticker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,33 @@ func TestTicker(t *testing.T) {

// ASSERT
assert.ErrorContains(t, err, "panic during ticker run: oops")
// assert that we get error with the correct line number
assert.ErrorContains(t, err, "ticker_test.go:142")
})

t.Run("Nil panic", func(t *testing.T) {
// ARRANGE
// Given a context
ctx := context.Background()

// And a ticker
ticker := New(durSmall, func(_ context.Context, _ *Ticker) error {
var a func()
a()
return nil
})

// ACT
err := ticker.Run(ctx)

// ASSERT
assert.ErrorContains(
t,
err,
"panic during ticker run: runtime error: invalid memory address or nil pointer dereference",
)
// assert that we get error with the correct line number
assert.ErrorContains(t, err, "ticker_test.go:162")
})

t.Run("Run as a single call", func(t *testing.T) {
Expand Down

0 comments on commit 77cf636

Please sign in to comment.