提交最初版的
This commit is contained in:
@@ -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()))
|
||||
}
|
||||
Reference in New Issue
Block a user