Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,12 @@ func (ee *exitError) ExitCode() int {
return ee.exitCode
}

// Unwrap returns the error given to [Exit], so that [errors.Is] and
// [errors.As] can inspect it through the ExitCoder wrapper.
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.
//
Expand Down
47 changes: 47 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"errors"
"fmt"
"io/fs"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -270,3 +271,49 @@ func TestHandleExitCoder_ExitCoderEmptyMessage(t *testing.T) {
assert.True(t, called)
assert.Empty(t, errBuf.String(), "expected no output to stderr for empty exit message")
}

func TestExit_Unwrap(t *testing.T) {
sentinel := errors.New("not found")

// The error given to Exit must stay reachable through the standard
// wrapping helpers (#1090).
tests := []struct {
name string
message any
wantMsg string // message of errors.Unwrap(err)
wantIs error // target for errors.Is, if any
wantAs any // target for errors.As, if any
}{
{
name: "error",
message: sentinel,
wantMsg: "not found",
wantIs: sentinel,
},
{
name: "error chain",
message: &fs.PathError{Op: "open", Path: "x", Err: fs.ErrNotExist},
wantMsg: "open x: file does not exist",
wantIs: fs.ErrNotExist,
wantAs: new(*fs.PathError),
},
{
name: "non-error message",
message: "boom",
wantMsg: "boom",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := Exit(tt.message, 2)

assert.EqualError(t, errors.Unwrap(err), tt.wantMsg)
if tt.wantIs != nil {
assert.ErrorIs(t, err, tt.wantIs)
}
if tt.wantAs != nil {
assert.ErrorAs(t, err, tt.wantAs)
}
})
}
}