Files
meredith 31d1b136ce [SCAN-81] Report ChunkUnit Panics (#4367)
* Add common.RecoverWithHandler

Allows panic recovery that still reports to Sentry, with caller-defined
handling afterward, so there's no confusion about chained recover() or
re-panicking.

* Catch ChunkUnit panics and include them in report

Keeps panics showing in Sentry, and includes panics in existing
first-fatal-error behavior, but does not propagate panics further
upward any longer.

* Test SourceManager ChunkUnit panic reporting
2025-08-06 10:33:45 -05:00

64 lines
1.8 KiB
Go

package common
import (
"fmt"
"os"
"runtime/debug"
"time"
"github.com/getsentry/sentry-go"
"github.com/trufflesecurity/trufflehog/v3/pkg/context"
)
// Recover handles panics and reports to Sentry.
func Recover(ctx context.Context) {
if err := recover(); err != nil {
panicStack := string(debug.Stack())
if eventID := sentry.CurrentHub().Recover(err); eventID != nil {
ctx.Logger().Info("panic captured", "event_id", *eventID)
}
ctx.Logger().Error(fmt.Errorf("panic"), panicStack,
"recover", err,
)
if !sentry.Flush(time.Second * 5) {
ctx.Logger().Info("sentry flush failed")
}
}
}
// RecoverWithHandler handles panics and reports to Sentry, then turns control
// over to a provided function. This permits extra reporting in the same scope
// without re-panicking, as recover() clears the state after it's called. Does
// NOT block to flush sentry report.
func RecoverWithHandler(ctx context.Context, callback func(error)) {
if err := recover(); err != nil {
panicStack := string(debug.Stack())
if eventID := sentry.CurrentHub().Recover(err); eventID != nil {
ctx.Logger().Info("panic captured", "event_id", *eventID)
}
ctx.Logger().Error(fmt.Errorf("panic"), panicStack,
"recover", err,
)
callback(fmt.Errorf("panic: %e", err))
}
}
// RecoverWithExit handles panics and reports to Sentry before exiting.
func RecoverWithExit(ctx context.Context) {
if err := recover(); err != nil {
panicStack := string(debug.Stack())
if eventID := sentry.CurrentHub().Recover(err); eventID != nil {
ctx.Logger().Info("panic captured", "event_id", *eventID)
}
ctx.Logger().Error(fmt.Errorf("panic"), "recovered from panic before exiting",
"stack-trace", panicStack,
"recover", err,
)
if !sentry.Flush(time.Second * 5) {
ctx.Logger().Info("sentry flush failed")
}
os.Exit(1)
}
}