Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Formatter interface #40

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
31 changes: 31 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,37 @@ func (p *Error) Error() string {
return output.String()
}

func (p *Error) Format(f fmt.State, verb rune) {
var s string

switch verb {
case 's', 'v':
if f.Flag('+') {
s = p.VerboseString()
} else if f.Flag('#') {
s = p.GoString()
} else {
s = p.Error()
}
}

if s == "" {
fmt.Fprint(f, p)
} else {
_, _ = f.Write([]byte(s))
}
}

func (p *Error) GoString() string {
isRetryable := "nil"
if p.IsRetryable != nil {
isRetryable = fmt.Sprintf("%#v", *p.IsRetryable)
}
return fmt.Sprintf("&terrors.Error{Code: %q, Message: %q, Params: %#v, StackFrames: %#v, IsRetryable: %s, cause: %#v}",
p.Code, p.Message, p.Params, p.StackFrames, isRetryable, p.cause,
)
}

func (p *Error) legacyErrString() string {
if p == nil {
return ""
Expand Down
19 changes: 19 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -481,3 +481,22 @@ func TestRetryable(t *testing.T) {
})
}
}

func TestFormat(t *testing.T) {
err := New("test", "Test", map[string]string{"flavour": "banana"})

assert.Equal(t, err.Error(),
fmt.Sprintf("%v", err))
assert.Equal(t, err.VerboseString(),
fmt.Sprintf("%+v", err))

goStringErr := fmt.Sprintf("%#v", err)
goStringErrPrefix := `&terrors.Error{Code: "test", Message: "Test", Params: map[string]string{"flavour":"banana"}, StackFrames: []*stack.Frame{`
assert.Equal(t, goStringErrPrefix, goStringErr[0:len(goStringErrPrefix)])

goStringErrSuffix := `}, IsRetryable: false, cause: <nil>}`
assert.Equal(t, goStringErrSuffix, goStringErr[len(goStringErr)-len(goStringErrSuffix):])

assert.Equal(t, err.Error(),
fmt.Sprintf("%d", err))
}
13 changes: 13 additions & 0 deletions stack/stack.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,19 @@ type Frame struct {

type Stack []*Frame

func (s Stack) GoString() string {
b := strings.Builder{}

if len(s) > 0 {
b.WriteString(fmt.Sprintf("&%#v", *s[0]))
for _, f := range s[1:] {
b.WriteString(fmt.Sprintf(", &%#v", *f))
}
}

return fmt.Sprintf("[]*stack.Frame{%s}", b.String())
}

func BuildStack(skip int) Stack {
stack := make(Stack, 0)

Expand Down