Skip to content

Commit

Permalink
api: wrap underlying EtcdError error
Browse files Browse the repository at this point in the history
Without wrapping, using `errors.Is()` (or even trying to compare the error with
`==`) fails as EtcdError swallows the underlying error.

Signed-off-by: Ivan Valdes <[email protected]>
  • Loading branch information
ivanvc committed Sep 12, 2024
1 parent fdbde77 commit c837473
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
11 changes: 8 additions & 3 deletions api/v3rpc/rpctypes/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,9 @@ var (
// EtcdError defines gRPC server errors.
// (https://github.com/grpc/grpc-go/blob/master/rpc_util.go#L319-L323)
type EtcdError struct {
code codes.Code
desc string
code codes.Code
desc string
wrappedError error
}

// Code returns grpc/codes.Code.
Expand All @@ -253,6 +254,10 @@ func (e EtcdError) Error() string {
return e.desc
}

func (e EtcdError) Unwrap() error {
return e.wrappedError
}

func Error(err error) error {
if err == nil {
return nil
Expand All @@ -268,7 +273,7 @@ func Error(err error) error {
} else {
desc = verr.Error()
}
return EtcdError{code: ev.Code(), desc: desc}
return EtcdError{code: ev.Code(), desc: desc, wrappedError: err}
}

func ErrorDesc(err error) string {
Expand Down
18 changes: 18 additions & 0 deletions api/v3rpc/rpctypes/error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package rpctypes

import (
"errors"
"testing"

"google.golang.org/grpc/codes"
Expand All @@ -40,3 +41,20 @@ func TestConvert(t *testing.T) {
t.Fatalf("expected them to be equal, got %v / %v", ev2.Code(), e3.(EtcdError).Code())
}
}

func TestComparingWrappedError(t *testing.T) {
errTest := errors.New("test error")
e1 := Error(ErrGRPCEmptyKey)
e2 := Error(status.Error(codes.InvalidArgument, "etcdserver: key is not provided"))
e3 := Error(errTest)

if !errors.Is(e1, ErrGRPCEmptyKey) {
t.Fatalf("expected %v to be an ErrGRPCEmptyKey wrapped error", e1)
}
if !errors.Is(e2, ErrGRPCEmptyKey) {
t.Fatalf("expected %v to be an ErrGRPCEmptyKey wrapped error", e1)
}
if !errors.Is(e3, errTest) {
t.Fatalf("expected %v to be an errTest wrapped error", e3)
}
}

0 comments on commit c837473

Please sign in to comment.