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

Capability to check for .env file not found error and other possible errors #101

Closed
EstebanBorai opened this issue May 23, 2020 · 2 comments · May be fixed by #143
Closed

Capability to check for .env file not found error and other possible errors #101

EstebanBorai opened this issue May 23, 2020 · 2 comments · May be fixed by #143

Comments

@EstebanBorai
Copy link

Description

When running gotdotenv.Load:

func Load(filenames ...string) (err error) {

Theres no way to check for a "FileNotFound" error.
godotenv panics as follows:

➜  server git:(master) ✗ go run main.go
panic: open .env: no such file or directory

goroutine 1 [running]:
main.main()
	.../server/main.go:12 +0xa9
exit status 2

Possible Solution

A possible solution would be to enumerate errors:

var (
        // EnvFileNotFound returns a "env file not found". Happens when godotenv is not able to find a .env file in the cwd
	EnvFileNotFound = errors.New("env file not found")
)

Then provide a ErrorIs like function, for example:

	err := godotenv.Load()

	if err != nil {
		if godotenv.ErrorIs(godotenv.EnvFileNotFound, err) {
                    // Do something
                } else {
		    return nil, err
                }
	}

Thanks in advance!

@cthompson527
Copy link

This works for me:

	err := godotenv.Load()
	if os.IsNotExist(err) {
		log.Fatalf(".env does not exist")
	}

@EstebanBorai
Copy link
Author

I think that does the work, but I'm more focused in something beyond this specific error. And improve error handling by using either an error variable or a handy function to discriminate the error type.

I imagine something like:

package error

// Error returned when GoDotEnv is unable to find the .env file
var EnvFileNotFound error = errors.New(".env file not found")

// Checks if the error is a `EnvFileNotFound` error
func IsEnvFileNotFoundError(err error) bool {
  return err == EnvFileNotFound
}

WDYT?

@EstebanBorai EstebanBorai closed this as not planned Won't fix, can't repro, duplicate, stale Jan 26, 2023
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

Successfully merging a pull request may close this issue.

2 participants