Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于 goroutine 包中 GoWithRecover 函数拆分 #82

Open
cyb0225 opened this issue Jun 9, 2023 · 0 comments
Open

关于 goroutine 包中 GoWithRecover 函数拆分 #82

cyb0225 opened this issue Jun 9, 2023 · 0 comments

Comments

@cyb0225
Copy link

cyb0225 commented Jun 9, 2023

pkg/utils/goroutine.go

Lines 41 to 60 in e3528ea

func GoWithRecover(handler func(), recoverHandler func(r interface{})) {
go func() {
defer func() {
if r := recover(); r != nil {
recoverLogger(os.Stderr, r)
if recoverHandler != nil {
go func() {
defer func() {
if p := recover(); p != nil {
recoverLogger(os.Stderr, p)
}
}()
recoverHandler(r)
}()
}
}
}()
handler()
}()
}

这里的 GoWithRecover 是不是拆成两个函数比较好,我在使用 errgroup 需要传入裸函数,这样拆分可以使用到 recover 机制,同时是否开启 goroutine 交给用户决定。

 func GoWithRecover(handler func(), recoverHandler func(r interface{})) { 
 	go func() { 
 		WithRecover(handler, recoverHandler)
 	}() 
 } 

func WithRecover(handler func(), recoverHandler func(r interface{})) {
              defer func() { 
 			if r := recover(); r != nil { 
 				recoverLogger(os.Stderr, r) 
 				if recoverHandler != nil { 
 					go func() { 
 						defer func() { 
 							if p := recover(); p != nil { 
 								recoverLogger(os.Stderr, p) 
 							} 
 						}() 
 						recoverHandler(r) 
 					}() 
 				} 
 			} 
 		}() 
 		handler() 
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant