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

Avoid Using panic for Error Handling #612

Open
oswaldom-code opened this issue Mar 18, 2025 · 0 comments
Open

Avoid Using panic for Error Handling #612

oswaldom-code opened this issue Mar 18, 2025 · 0 comments

Comments

@oswaldom-code
Copy link
Contributor

Description

Currently, some functions use panic to handle errors. While panic is useful for unrecoverable situations, it is generally not idiomatic in Go for handling expected errors. This approach can be problematic because:

  1. It disrupts the normal control flow of the application.
  2. It forces users to wrap function calls with defer/recover, making error handling more complex.
  3. It reduces flexibility, as users might want to handle errors in different ways instead of being forced into a panic.
  4. The Go standard library follows a convention of returning errors instead of panicking, except for cases where failure is truly exceptional.

Proposed Solution

  • Replace panic with proper error handling by returning error values.

I’d be happy to submit a PR addressing this issue by refactoring the affected functions. Please let me know if this aligns with the project’s philosophy.

Command executed to detect the use of panic:

grep -r -n --exclude='*_test.go' --exclude='*.md' 'panic' . | sed 's|//.*||' | grep -vE '^\s*$'

Result:

➜  lo git:(master) grep -r -n --exclude='*_test.go' --exclude='*.md' 'panic' . | sed 's|//.*||' | grep -vE '^\s*$'
./slice.go:209:         panic("Second parameter must be greater than 0")
./slice.go:610:
./slice.go:633:
./errors.go:31:
./errors.go:45:                 panic(message)
./errors.go:51:                 panic(message + ": " + e.Error())
./errors.go:53:                 panic(e.Error())
./errors.go:57:         panic("must: invalid err type '" + reflect.TypeOf(err).Name() + "', should either be a bool or an error")
./errors.go:62:
./errors.go:311:
./string.go:35:         panic("lo.RandomString: Size parameter must be greater than 0")
./string.go:38:         panic("lo.RandomString: Charset parameter must not be empty")
./string.go:119:                panic("lo.ChunkString: Size parameter must be greater than 0")
./map.go:254:           panic("The chunk size must be greater than 0")
./concurrency.go:22:            panic("unexpected arguments")
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