Files

30 lines
771 B
Go
Raw Permalink Normal View History

2025-07-03 06:57:00 +00:00
package safe
import (
"context"
"runtime/debug"
"fmt"
)
// Go starts a recoverable goroutine
func Go(ctx context.Context, f func(ctx context.Context)) {
GoWithRecover(ctx, f, defaultRecoverGoroutine)
}
// GoWithRecover starts a recoverable goroutine using given customRecover() function
func GoWithRecover(ctx context.Context, goroutine func(ctx context.Context), customRecover func(ctx context.Context, err interface{})) {
go func() {
defer func() {
if err := recover(); err != nil {
customRecover(ctx, err)
}
}()
goroutine(ctx)
}()
}
func defaultRecoverGoroutine(ctx context.Context, err interface{}) {
fmt.Println("SafeGo panic recover! err: %+v", err)
fmt.Println( "SafeGo Stack:%+v", string(debug.Stack()))
}