Skip to content

Commit bb2e3ea

Browse files
committed
errors: don't print an empty line for Exit with empty message
When HandleExitCoder received an ExitCoder whose Error() returned an empty string (e.g. cli.Exit("", code)), it still called fmt.Fprintln(ErrWriter, err) which wrote a bare newline to stderr. Guard the print with a check on the error message so that an empty message produces no output at all. Fixes #2263 Signed-off-by: alliasgher <alliasgher123@gmail.com>
1 parent 760eb19 commit bb2e3ea

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

errors.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -150,10 +150,12 @@ func HandleExitCoder(err error) {
150150
}
151151

152152
if exitErr, ok := err.(ExitCoder); ok {
153-
if _, ok := exitErr.(ErrorFormatter); ok {
154-
_, _ = fmt.Fprintf(ErrWriter, "%+v\n", err)
155-
} else {
156-
_, _ = fmt.Fprintln(ErrWriter, err)
153+
if msg := err.Error(); msg != "" {
154+
if _, ok := exitErr.(ErrorFormatter); ok {
155+
_, _ = fmt.Fprintf(ErrWriter, "%+v\n", err)
156+
} else {
157+
_, _ = fmt.Fprintln(ErrWriter, err)
158+
}
157159
}
158160
OsExiter(exitErr.ExitCode())
159161
return

errors_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,3 +232,28 @@ func TestErrRequiredFlags_Error(t *testing.T) {
232232
expectedMsg = "Required flag \"flag1\" not set"
233233
assert.Equal(t, expectedMsg, err.Error())
234234
}
235+
236+
// TestHandleExitCoder_EmptyMessage is a regression test for
237+
// https://github.com/urfave/cli/issues/2263.
238+
// HandleExitCoder must not print an empty line to ErrWriter when the ExitCoder
239+
// message is empty (e.g. cli.Exit("", code)).
240+
func TestHandleExitCoder_EmptyMessage(t *testing.T) {
241+
called := false
242+
243+
OsExiter = func(rc int) {
244+
if !called {
245+
called = true
246+
}
247+
}
248+
ErrWriter = &bytes.Buffer{}
249+
250+
defer func() {
251+
OsExiter = fakeOsExiter
252+
ErrWriter = fakeErrWriter
253+
}()
254+
255+
HandleExitCoder(Exit("", 2))
256+
257+
assert.True(t, called)
258+
assert.Empty(t, ErrWriter.(*bytes.Buffer).String(), "expected no output for empty-message exit")
259+
}

0 commit comments

Comments
 (0)