fix: enhance error.FromError (#1451)

add converting support for grpc status which not contain details with type `errdetails.ErrorInfo`
pull/1452/head
pwli 3 years ago committed by GitHub
parent 2024fa7cdb
commit 378d1ee3c7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 14
      errors/errors.go
  2. 11
      errors/errors_test.go

@ -5,7 +5,6 @@ import (
"fmt"
httpstatus "github.com/go-kratos/kratos/v2/transport/http/status"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
@ -102,16 +101,19 @@ func FromError(err error) *Error {
}
gs, ok := status.FromError(err)
if ok {
ret := New(
httpstatus.FromGRPCCode(gs.Code()),
UnknownReason,
gs.Message(),
)
for _, detail := range gs.Details() {
switch d := detail.(type) {
case *errdetails.ErrorInfo:
return New(
httpstatus.FromGRPCCode(gs.Code()),
d.Reason,
gs.Message(),
).WithMetadata(d.Metadata)
ret.Reason = d.Reason
return ret.WithMetadata(d.Metadata)
}
}
return ret
}
return New(UnknownCode, UnknownReason, err.Error())
}

@ -5,6 +5,10 @@ import (
"fmt"
"net/http"
"testing"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/grpc/test/grpc_testing"
)
func TestError(t *testing.T) {
@ -46,4 +50,11 @@ func TestError(t *testing.T) {
if se.Reason != "reason" {
t.Errorf("got %+v want %+v", se, err)
}
gs2, _ := status.New(codes.InvalidArgument, "bad request").WithDetails(&grpc_testing.Empty{})
se2 := FromError(gs2.Err())
// codes.InvalidArgument should convert to http.StatusBadRequest
if se2.Code != http.StatusBadRequest {
t.Errorf("convert code err, got %d want %d", UnknownCode, http.StatusBadRequest)
}
}

Loading…
Cancel
Save