@@ -28,15 +28,16 @@ package goutil
2828
2929import (
3030 "context"
31- "errors"
3231 "fmt"
3332 "runtime/debug"
3433 "sync"
34+
35+ "github.com/go-spring/spring-base/util"
3536)
3637
3738// OnPanic is a global callback function triggered when a panic occurs.
38- var OnPanic = func (ctx context.Context , r any ) {
39- fmt .Printf ("panic: %v\n %s\n " , r , debug . Stack () )
39+ var OnPanic = func (ctx context.Context , r any , stack [] byte ) {
40+ fmt .Printf ("panic: %v\n %s\n " , r , stack )
4041}
4142
4243/********************************** go ***************************************/
@@ -72,7 +73,7 @@ func Go(ctx context.Context, f func(ctx context.Context)) *Status {
7273 defer func () {
7374 if r := recover (); r != nil {
7475 if OnPanic != nil {
75- OnPanic (ctx , r )
76+ OnPanic (ctx , r , debug . Stack () )
7677 }
7778 }
7879 }()
@@ -81,24 +82,6 @@ func Go(ctx context.Context, f func(ctx context.Context)) *Status {
8182 return s
8283}
8384
84- // GoFunc runs a goroutine safely with panic recovery.
85- // It ensures the process does not crash due to an uncaught panic in the goroutine.
86- func GoFunc (f func ()) * Status {
87- s := newStatus ()
88- go func () {
89- defer s .done ()
90- defer func () {
91- if r := recover (); r != nil {
92- if OnPanic != nil {
93- OnPanic (context .Background (), r )
94- }
95- }
96- }()
97- f ()
98- }()
99- return s
100- }
101-
10285/******************************* go with value *******************************/
10386
10487// ValueStatus provides a mechanism to wait for a goroutine that returns a value and an error.
@@ -135,10 +118,11 @@ func GoValue[T any](ctx context.Context, f func(ctx context.Context) (T, error))
135118 defer s .done ()
136119 defer func () {
137120 if r := recover (); r != nil {
121+ stack := debug .Stack ()
138122 if OnPanic != nil {
139- OnPanic (ctx , r )
123+ OnPanic (ctx , r , stack )
140124 }
141- s .err = errors . New ( "panic occurred" )
125+ s .err = util . FormatError ( nil , "panic: %v \n %s" , r , stack )
142126 }
143127 }()
144128 s .val , s .err = f (ctx )
0 commit comments