lo
lo copied to clipboard
Proposal: Add defer recover to handle panic
When we use some method like GroupBy, we pass an iteratee function, which could come to panic.
I proposal to add a defer recover to catch the exception.
So the GroupBy will become:
func GroupBy[T any, U comparable](collection []T, iteratee func(item T) U) map[U][]T {
var index int
defer func() {
if e := recover(); e != nil {
log.Printf("No.%d item panic: %v", index, e)
return
}
}()
result := map[U][]T{}
for _, item := range collection {
key := iteratee(item)
index++
result[key] = append(result[key], item)
}
return result
}
I don't think we should handle panics in helpers. Some developers may let iteratee crash and handle errors by themselves later.
May I suggest using lo.Try() instead?
I don't close the issue, since I'm open to further discussions ;)
what if we had a global defer function? although this seems very generic and solves not so much.
var globalRecoveryFunc = func() {}
func SetGlobalDefer(f func()) {
globalRecoveryFunc = f
}
func Map[T any, R any](collection []T, iteratee func(item T, index int) R) []R {
result := make([]R, len(collection))
defer globalRecoveryFunc()
...
}
in main.go
lo.SetGlobalDefer(func() {
if e := recover(); e != nil {
fmt.Println("im the new defer handler", e)
}
})
Are there any other use cases other than recovery of panics?