Skip to content

refactor: Handle errors returned by viper.BindPFlag and viper.BindEnv #54

@electather

Description

@electather

Problem / motivation

In cmd/root.go and cmd/mcp/flags.go, multiple viper.BindPFlag() and viper.BindEnv() calls silently discard the returned error:

// cmd/root.go
viper.BindPFlag("seerr.server", RootCmd.PersistentFlags().Lookup("server"))
viper.BindPFlag("seerr.api_key", RootCmd.PersistentFlags().Lookup("api-key"))
viper.BindPFlag("verbose", RootCmd.PersistentFlags().Lookup("verbose"))
viper.BindEnv("seerr.server", "SEERR_SERVER")
viper.BindEnv("seerr.api_key", "SEERR_API_KEY")

// cmd/mcp/flags.go
viper.BindPFlag(f.ViperKey, flag)

While these rarely fail in practice, silently ignoring errors is a Go anti-pattern and can mask configuration bugs (e.g. a typo in a flag name causing Lookup() to return nil).

Proposed solution

Check and handle the returned errors. Since these are called during init() / cobra.OnInitialize, a panic or cobra.CheckErr is appropriate — a bind failure is a programmer error, not a runtime condition:

cobra.CheckErr(viper.BindPFlag("seerr.server", RootCmd.PersistentFlags().Lookup("server")))
cobra.CheckErr(viper.BindPFlag("seerr.api_key", RootCmd.PersistentFlags().Lookup("api-key")))
cobra.CheckErr(viper.BindPFlag("verbose", RootCmd.PersistentFlags().Lookup("verbose")))

Files affected:

  • cmd/root.go
  • cmd/mcp/flags.go (BindFlags function)

Alternatives considered

Wrap in a helper like mustBind() — functionally equivalent but adds an extra function.

Additional context

Most Go linters (e.g. errcheck, golangci-lint) will flag these as unhandled errors.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions