Skip to content
This repository has been archived by the owner on Sep 6, 2022. It is now read-only.

Commit

Permalink
test: add a panic catcher test
Browse files Browse the repository at this point in the history
  • Loading branch information
Stebalien committed Apr 17, 2022
1 parent bee2c55 commit 5b5d026
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
5 changes: 4 additions & 1 deletion internal/catch/catch.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ package catch

import (
"fmt"
"io"
"os"
"runtime/debug"
)

var panicWriter io.Writer = os.Stderr

func CatchAndLog(err *error, where string) {
if rerr := recover(); rerr != nil {
fmt.Fprintf(os.Stderr, "caught panic: %s\n%s\n", rerr, debug.Stack())
fmt.Fprintf(panicWriter, "caught panic: %s\n%s\n", rerr, debug.Stack())
*err = fmt.Errorf("panic in %s: %s", where, rerr)
}
}
28 changes: 28 additions & 0 deletions internal/catch/catch_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package catch

import (
"bytes"
"testing"

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

func TestCatch(t *testing.T) {
buf := new(bytes.Buffer)

oldPanicWriter := panicWriter
t.Cleanup(func() { panicWriter = oldPanicWriter })
panicWriter = buf

panicAndCatch := func() (err error) {
defer CatchAndLog(&err, "somewhere")

panic("here")
}

err := panicAndCatch()
require.Error(t, err)
require.Contains(t, err.Error(), "panic in somewhere: here")

require.Contains(t, buf.String(), "caught panic: here")
}

0 comments on commit 5b5d026

Please sign in to comment.