diff --git a/errors/errors.go b/errors/errors.go index 8b2e7f55d..64466fcb0 100644 --- a/errors/errors.go +++ b/errors/errors.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()) } diff --git a/errors/errors_test.go b/errors/errors_test.go index b92879505..1408ec67d 100644 --- a/errors/errors_test.go +++ b/errors/errors_test.go @@ -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) + } }