commit 5ddd403fc1d107d125d6236111c81844cd489d88 Author: yun Date: Thu Jul 3 06:57:00 2025 +0000 提交最初版的 diff --git a/safex.go b/safex.go new file mode 100644 index 0000000..5562cb5 --- /dev/null +++ b/safex.go @@ -0,0 +1,29 @@ +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())) +}