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

Command Execute error not returned to parser. #46

Closed
rlmcpherson opened this issue Dec 9, 2013 · 1 comment
Closed

Command Execute error not returned to parser. #46

rlmcpherson opened this issue Dec 9, 2013 · 1 comment

Comments

@rlmcpherson
Copy link
Contributor

Is there any way to call the Execute function on a command so that it will exit with an error? Currently, it just prints the error but does not result in a non-zero exit status for the process. See https://github.com/jessevdk/go-flags/blob/master/parser.go#L198

Otherwise, is there some way to use the Command interface to get an error back? From the documentation, it would seem that way (https://github.com/jessevdk/go-flags/blob/master/command.go#L21) but I don't think it actually does this.

@jessevdk
Copy link
Owner

jessevdk commented Dec 9, 2013

You can simply check the error returned from p.Parse(), like this:

package main

import (
    "fmt"
    "github.com/jessevdk/go-flags"
)

type Add struct {
}

func (a *Add) Execute(args []string) error {
    return fmt.Errorf("Some customized error")
}

func main() {
    var opt struct {
    }

    p := flags.NewParser(&opt, flags.Default)

    p.AddCommand("add", "Adding it", "More adding it", &Add{})

    if _, err := p.Parse(); err != nil {
        fmt.Printf("%#v\n", err)
    }
}

If you need to discriminate between your errors and those of the flags package, then you can use if _, ok := err.(flags.Error); !ok ...

Otherwise, you can also simply call os.Exit(1) from your Execute handler, nothing wrong with that. Just print the error yourself (flags just does fmt.Fprintln(os.Stderr, err), but checks for the PrintErrors option).

@jessevdk jessevdk closed this as completed Dec 9, 2013
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

2 participants