godotenv
godotenv copied to clipboard
Capability to check for .env file not found error and other possible errors
Description
When running gotdotenv.Load
:
https://github.com/joho/godotenv/blob/d6ee6871f21dd95e76563a90f522ce9fe75443f8/godotenv.go#L41
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!
This works for me:
err := godotenv.Load()
if os.IsNotExist(err) {
log.Fatalf(".env does not exist")
}
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?