Feature:(issue_1090): Add unwrap for ExitCoder (#1545)

* Feature:(issue_1090): Add unwrap for ExitCoder

* Add simple test for error
This commit is contained in:
dearchap 2022-10-28 09:15:54 -04:00 committed by GitHub
parent 63cb372cce
commit c344b46a29
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 3 deletions

View File

@ -83,7 +83,7 @@ type ExitCoder interface {
type exitError struct {
exitCode int
message interface{}
err error
}
// 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
// OsExiter function.
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{
message: message,
err: err,
exitCode: exitCode,
}
}
func (ee *exitError) Error() string {
return fmt.Sprintf("%v", ee.message)
return ee.err.Error()
}
func (ee *exitError) ExitCode() int {
return ee.exitCode
}
func (ee *exitError) Unwrap() error {
return ee.err
}
// HandleExitCoder handles errors implementing ExitCoder by printing their
// 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)
}
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) {
exitCode := 0
called := false