cli
cli copied to clipboard
ExitCoder should implement Unwrap
Checklist
- [x] Are you running the latest v2 release? The list of releases is here.
- [x] Did you check the manual for your release? The v2 manual is here
- [x] Did you perform a search about this feature? Here's the Github guide about searching.
What problem does this solve?
In golang v1.13 the notion of error wrapping was introduced with the following optional method signature on error
types: func (*T) Unwrap error
. The ExitCoder
type is very similar to a wrapped error with addition information (the exit code), so it seems like a good addition.
A long term consideration (for this package's v3) might be to change the implementation of ExitCoder
to be:
type exitError struct {
exitCode int
err error
}
Makes sense 👍 I'm wondering if there's something we can do about this in v2? But you should definitely comment about this on the v3 thread! https://github.com/urfave/cli/issues/833
We can absolutely support this in v2 in a backward compatible way by adding a new function:
type exitError struct {
err error
exitCode int
}
func (e exitError) Error() string {
return e.err.Error()
}
func (e exitError) ExitCode() int {
return e.exitCode
}
func (e exitError) Unwrap() error {
return err.err
}
// This could be a preferred alternative to Exit, or just an alternative.
func WrapErrorWithExitCodeButAlsoWithBetterFunctionName(err error, exitCode int) error {
return exitError{
err: err,
exitCode: exitCode,
}
}
// Exit can now return the new version of the unexported type without breaking the interface
func Exit(message interface{}, exitCode int) ExitCoder {
// If we wanted to get fancy here, we could check if the "message"
// was already an error, and if so, wrap it. I'm coding in GitHub so
// I'm not going to write it out, but I recommend it
return exitError{
err: fmt.Errorf("%v", message),
exitCode: exitCode,
}
}
WrapErrorWithExitCodeButAlsoWithBetterFunctionName
😆
I think for v2
the simplest solution would be the following change to the Exit
function.
// Exit returns an ExitCoder. If err is an error then it is directly wrapped, otherwise err is
// treated as an error message and a new error is created.
//
// This is done to be backwards comparable with previous v2 versions.
func Exit(err interface{}, exitCode int) ExitCoder {
if e, ok := err.(error); ok {
return exitError {
err: e,
exitCode: exitCode,
}
}
return exitError {
err: fmt.Errorf("%v", message),
exitCode: exitCode,
}
}
This issue or PR has been automatically marked as stale because it has not had recent activity. Please add a comment bumping this if you're still interested in it's resolution! Thanks for your help, please let us know if you need anything else.
Closing this as it has become stale.