Skip to content

Commit

Permalink
Merge pull request #50 from monzo/add-error-message-method
Browse files Browse the repository at this point in the history
Add ErrorMessage() method
  • Loading branch information
Will Sewell authored Sep 22, 2023
2 parents a3df3e6 + ee04ef7 commit 4a94093
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
11 changes: 9 additions & 2 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,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) {
Expand Down
28 changes: 28 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,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
Expand Down

0 comments on commit 4a94093

Please sign in to comment.