Merge commit 'c344b46' into v3-porting

This commit is contained in:
Dan Buch 2022-11-07 08:34:56 -05:00
commit 84af977350
Signed by: meatballhat
GPG Key ID: A12F782281063434
2 changed files with 37 additions and 3 deletions

View File

@ -83,7 +83,7 @@ type ExitCoder interface {
type exitError struct { type exitError struct {
exitCode int exitCode int
message interface{} err error
} }
// NewExitError calls Exit to create a new ExitCoder. // NewExitError calls Exit to create a new ExitCoder.
@ -101,20 +101,35 @@ func NewExitError(message interface{}, exitCode int) ExitCoder {
// by overriding the ExitErrHandler function on an App or the package-global // by overriding the ExitErrHandler function on an App or the package-global
// OsExiter function. // OsExiter function.
func Exit(message interface{}, exitCode int) ExitCoder { func Exit(message interface{}, exitCode int) ExitCoder {
var err error
switch e := message.(type) {
case ErrorFormatter:
err = fmt.Errorf("%+v", message)
case error:
err = e
default:
err = fmt.Errorf("%+v", message)
}
return &exitError{ return &exitError{
message: message, err: err,
exitCode: exitCode, exitCode: exitCode,
} }
} }
func (ee *exitError) Error() string { func (ee *exitError) Error() string {
return fmt.Sprintf("%v", ee.message) return ee.err.Error()
} }
func (ee *exitError) ExitCode() int { func (ee *exitError) ExitCode() int {
return ee.exitCode return ee.exitCode
} }
func (ee *exitError) Unwrap() error {
return ee.err
}
// HandleExitCoder handles errors implementing ExitCoder by printing their // HandleExitCoder handles errors implementing ExitCoder by printing their
// message and calling OsExiter with the given exit code. // message and calling OsExiter with the given exit code.
// //

View File

@ -45,6 +45,25 @@ func TestHandleExitCoder_ExitCoder(t *testing.T) {
expect(t, called, true) expect(t, called, true)
} }
func TestHandleExitCoder_ErrorExitCoder(t *testing.T) {
exitCode := 0
called := false
OsExiter = func(rc int) {
if !called {
exitCode = rc
called = true
}
}
defer func() { OsExiter = fakeOsExiter }()
HandleExitCoder(Exit(errors.New("galactic perimeter breach"), 9))
expect(t, exitCode, 9)
expect(t, called, true)
}
func TestHandleExitCoder_MultiErrorWithExitCoder(t *testing.T) { func TestHandleExitCoder_MultiErrorWithExitCoder(t *testing.T) {
exitCode := 0 exitCode := 0
called := false called := false