Error Handling
Zero Panics
Section titled “Zero Panics”Every constructor that can fail returns (value, error), for example v5.NewCLI[AppConfig](...) returns (*v5.CLI[AppConfig], error). There are no Must* panic variants, and handlers are always RunE-shaped functions.
The Error-Print Contract
Section titled “The Error-Print Contract”| Rule | Behavior |
|---|---|
| Printed once | fang renders the error when enabled (the default), plain Cobra when disabled |
| No usage on error | SilenceUsage is true by default; WithoutSilenceUsage() re-enables it |
| Never re-print | the error returned by Execute is for exit-code mapping only |
| Hints | a Hint: line follows the error when cmdguard knows the fix |
ExecuteAndExit is the blessed entry point. When you must run code before the process exits, map the error yourself:
package main
import ( "context" "os"
"github.com/larsartmann/cmdguard/v5/pkg/cmdguard/v5")
type AppConfig struct { Verbose bool `flag:"verbose" short:"v" help:"Enable verbose output"`}
func main() { cli, err := v5.NewCLI[AppConfig]("app", "My app", AppConfig{}) if err != nil { os.Exit(1) }
err = cli.Execute(context.Background())
// Flush logs, export audit data, or tear down here.
os.Exit(v5.ExitCode(err))}Do not print the returned error a second time; cmdguard already printed it.
Exit Codes
Section titled “Exit Codes”| Situation | Exit code |
|---|---|
nil error |
0 |
error without an ExitCoder |
1 |
ExitCoder with a non-zero code |
that code |
ExitCoder with code 0 |
1 (zero means no override) |
NewExitError validates the range 0-255 and returns an error otherwise:
exitErr, err := v5.NewExitError(42, errors.New("config missing required field"))if err != nil { return err // ErrInvalidExitCode: code outside 0-255}
return exitErrAny error implementing Error() string and ExitCode() int satisfies v5.ExitCoder, so domain errors can carry their own code.
ErrorHint(err) returns one actionable sentence, or an empty string when the error wraps no classified sentinel:
if hint := v5.ErrorHint(err); hint != "" { slog.Warn("command failed", "hint", hint)}Human-readable output prints a Hint: line after the error. WithoutErrorHints() disables that line; machine-readable output keeps the hint field.
Machine Error Codes
Section titled “Machine Error Codes”ErrorCode(err) returns a stable lowercase snake_case code for every documented sentinel. With a structured output format (--output json, jsonl, yaml, or toml) the error is emitted as a JSON envelope:
{ "error": { "type": "flag", "message": "required flag not set: name", "hint": "pass the flag on the command line, or set its env var or config-file value", "error_code": "required_flag", "code": 1 }}type is the error class, message the stable text, hint the fix, error_code the machine code, and code the process exit code.
Call v5.ErrorCode(err) in custom handlers to switch on the same code; it returns "" when the error wraps no sentinel.
Sentinel Errors
Section titled “Sentinel Errors”Sentinels are wrapped with fmt.Errorf("%w: ...", sentinel), so errors.Is reaches them through any number of layers:
errors.Is(err, v5.ErrInvalidCommand)errors.Is(err, v5.ErrMissingHandler)errors.Is(err, v5.ErrDuplicateCommand)errors.Is(err, v5.ErrConfigValidation)docs/ERROR_REFERENCE.md documents 62 sentinels with their codes and hints. The most common groups:
| Group | Examples |
|---|---|
| Command | ErrInvalidCommand, ErrMissingHandler, ErrDuplicateCommand, ErrMissingShort |
| Flags | ErrRequiredFlag, ErrInvalidEnum, ErrValueOutOfRange, ErrInvalidFlagDefault |
| Config | ErrConfigValidation, ErrConfigUnknownKey, ErrConfigFileParse |
| Services | ErrServiceRegistration, ErrServiceConstruction, ErrServiceNotFound |
Typed Errors
Section titled “Typed Errors”| Type | Constructor | Purpose |
|---|---|---|
CommandError |
NewCommandError(name, err) |
command name context |
FlagError |
NewFlagError(name, err) |
flag name context |
FlagError |
NewFlagErrorWithSuggestion(name, err, suggestion) |
flag context plus typo fix |
ConfigError |
NewConfigError(field, err) |
config field context |
EnumError |
NewEnumError(value, allowed) |
invalid enum value and allowed list |
DurationError |
NewDurationError(value, err) |
invalid duration |
ServiceError |
NewServiceError(serviceType, err) |
DI service failure |
ExitError |
NewExitError(code, err) |
custom exit code 0-255 |
All of them implement Unwrap(), so errors.Is and errors.AsType work:
flagErr, ok := errors.AsType[*v5.FlagError](err)if ok { log.Printf("flag %s: %s", flagErr.FlagName, flagErr.Suggestion)}Suggestions
Section titled “Suggestions”SuggestFlag(validNames, input) and SuggestCommand(validCommands, input) return a closest match plus true when one is within edit distance 3. NewFlagErrorWithSuggestion embeds that suggestion in the error text.
Error Aggregation
Section titled “Error Aggregation”ValidateConfig(cfg) joins every field failure under ErrConfigValidation, so one errors.Is(err, v5.ErrConfigValidation) check covers the group while each individual field error stays reachable.
Where to go next
Section titled “Where to go next”- Lifecycle and Signal Handling for exit paths and cleanup hooks
- Type-Safe Flags for the validation tags behind flag errors
- Middleware for recovery and timeout middleware
- API Reference for the full surface