Skip to content

Commit

Permalink
Add status.WithDescription (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
vearutop authored Dec 7, 2023
1 parent 7c57456 commit a96ea69
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
23 changes: 23 additions & 0 deletions status/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ func (c Code) Error() string {
return codeToMsg[c]
}

// Is implements interface for errors.Is.
func (c Code) Is(target error) bool {
return target == c //nolint:goerr113 // Target is expected to be plain status error.
}

type errorWithStatus struct {
err error
code Code
Expand Down Expand Up @@ -55,3 +60,21 @@ func Wrap(err error, code Code) error {
code: code,
}
}

type codeWithDescription struct {
Code
desc string
}

func (e codeWithDescription) Description() string {
return e.desc
}

// WithDescription augments status Code with textual description.
func WithDescription(code Code, description string) error {
e := codeWithDescription{}
e.Code = code
e.desc = description

return e
}
13 changes: 13 additions & 0 deletions status/error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,16 @@ func TestWrap(t *testing.T) {
func TestCode_Error(t *testing.T) {
assert.Equal(t, "deadline exceeded", status.DeadlineExceeded.Error())
}

func TestWithDescription(t *testing.T) {
err := status.WithDescription(status.AlreadyExists, "This is a description.")
assert.EqualError(t, err, "already exists")
assert.True(t, errors.Is(err, status.AlreadyExists))
assert.False(t, errors.Is(err, status.NotFound))

d, ok := err.(interface {
Description() string
})
assert.True(t, ok)
assert.Equal(t, "This is a description.", d.Description())
}

0 comments on commit a96ea69

Please sign in to comment.