lo icon indicating copy to clipboard operation
lo copied to clipboard

Proposal: Add defer recover to handle panic

Open donnol opened this issue 2 years ago • 2 comments

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
}

donnol avatar Mar 02 '23 07:03 donnol

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 ;)

samber avatar Mar 20 '23 17:03 samber

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?

RaddadZ avatar May 23 '23 09:05 RaddadZ