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

Return wrapped error with "%w" verb instead of "%s" #137

Open
code19m opened this issue Apr 2, 2024 · 0 comments
Open

Return wrapped error with "%w" verb instead of "%s" #137

code19m opened this issue Apr 2, 2024 · 0 comments

Comments

@code19m
Copy link

code19m commented Apr 2, 2024

func parseFile(path string, cfg interface{}) error {
	// open the configuration file
	f, err := os.OpenFile(path, os.O_RDONLY|os.O_SYNC, 0)
	if err != nil {
		return err
	}
	defer f.Close()

	// parse the file depending on the file type
	switch ext := strings.ToLower(filepath.Ext(path)); ext {
	case ".yaml", ".yml":
		err = ParseYAML(f, cfg)
	case ".json":
		err = ParseJSON(f, cfg)
	case ".toml":
		err = ParseTOML(f, cfg)
	case ".edn":
		err = parseEDN(f, cfg)
	case ".env":
		err = parseENV(f, cfg)
	default:
		return fmt.Errorf("file format '%s' doesn't supported by the parser", ext)
	}
	if err != nil {
		return fmt.Errorf("config file parsing error: %s", err.Error())
	}
	return nil
}

In this function, it would be better to return an error with the "%w" verb instead of "%s". In that case, when using cleanenv.ReadConfig, the returned error can be checked with the errors.Is(err, io.EOF) function.
Let's say I want to allow the user to leave the config file empty so that default values will be taken. But for this, I am now forced to check it with function like this:

func isEOFerr(err error) bool {
	return strings.HasSuffix(err.Error(), io.EOF.Error())
}
@code19m code19m changed the title Return wrapped io.EOF error instead Return wrapped error with "%w" verb instead of "%s" Apr 2, 2024
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