From ee04ef7fb0158ae6a7889ed72a36ac3baf132dfe Mon Sep 17 00:00:00 2001 From: Will Sewell Date: Fri, 22 Sep 2023 13:56:35 +0100 Subject: [PATCH] Add ErrorMessage() method This prints the same as Error(), but without the code prefix. This can be useful in cases where you want the messages of the causal chain, but not the prefix. Prefiously you'd have to do ``` strings.TrimPrefix(terr.Error(), terr.Code+": ") ``` a bit clunky. --- errors.go | 11 +++++++++-- errors_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/errors.go b/errors.go index a36747a..bae4daa 100644 --- a/errors.go +++ b/errors.go @@ -88,9 +88,16 @@ func (p *Error) Error() string { // new wrapping functionality) return p.legacyErrString() } - var next error = p + return fmt.Sprintf("%s: %s", p.Code, p.ErrorMessage()) +} + +// ErrorMessage returns a string message of the error. +// It will contain the error message, but not the code. If there is a causal +// chain, the message from each error in the chain will be added to the output. +func (p *Error) ErrorMessage() string { output := strings.Builder{} - output.WriteString(p.Code) + output.WriteString(p.Message) + var next error = p.cause for next != nil { output.WriteString(": ") switch typed := next.(type) { diff --git a/errors_test.go b/errors_test.go index 676cc7e..0254f55 100644 --- a/errors_test.go +++ b/errors_test.go @@ -454,6 +454,34 @@ func TestStackTrace(t *testing.T) { }) } +func TestErrorMessage(t *testing.T) { + cases := []struct { + desc string + terr Error + expected string + }{ + { + desc: "plain terror", + terr: Error{Code: "code", Message: "message"}, + expected: "message", + }, + { + desc: "terror with cause", + terr: Error{Code: "code", Message: "message", cause: &Error{ + Code: "code_inner", Message: "message_inner", + }}, + expected: "message: message_inner", + }, + } + + for _, tc := range cases { + t.Run(tc.desc, func(t *testing.T) { + msg := tc.terr.ErrorMessage() + assert.Equal(t, tc.expected, msg) + }) + } +} + func TestRetryable(t *testing.T) { cases := []struct { desc string