mirror of
https://github.com/go-kratos/kratos.git
synced 2026-05-22 10:15:24 +02:00
fix: enhance error.FromError (#1451)
add converting support for grpc status which not contain details with type `errdetails.ErrorInfo`
This commit is contained in:
+8
-6
@@ -5,7 +5,6 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
httpstatus "github.com/go-kratos/kratos/v2/transport/http/status"
|
httpstatus "github.com/go-kratos/kratos/v2/transport/http/status"
|
||||||
|
|
||||||
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||||
"google.golang.org/grpc/status"
|
"google.golang.org/grpc/status"
|
||||||
"google.golang.org/protobuf/proto"
|
"google.golang.org/protobuf/proto"
|
||||||
@@ -102,16 +101,19 @@ func FromError(err error) *Error {
|
|||||||
}
|
}
|
||||||
gs, ok := status.FromError(err)
|
gs, ok := status.FromError(err)
|
||||||
if ok {
|
if ok {
|
||||||
|
ret := New(
|
||||||
|
httpstatus.FromGRPCCode(gs.Code()),
|
||||||
|
UnknownReason,
|
||||||
|
gs.Message(),
|
||||||
|
)
|
||||||
for _, detail := range gs.Details() {
|
for _, detail := range gs.Details() {
|
||||||
switch d := detail.(type) {
|
switch d := detail.(type) {
|
||||||
case *errdetails.ErrorInfo:
|
case *errdetails.ErrorInfo:
|
||||||
return New(
|
ret.Reason = d.Reason
|
||||||
httpstatus.FromGRPCCode(gs.Code()),
|
return ret.WithMetadata(d.Metadata)
|
||||||
d.Reason,
|
|
||||||
gs.Message(),
|
|
||||||
).WithMetadata(d.Metadata)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return ret
|
||||||
}
|
}
|
||||||
return New(UnknownCode, UnknownReason, err.Error())
|
return New(UnknownCode, UnknownReason, err.Error())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,10 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
|
"google.golang.org/grpc/test/grpc_testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestError(t *testing.T) {
|
func TestError(t *testing.T) {
|
||||||
@@ -46,4 +50,11 @@ func TestError(t *testing.T) {
|
|||||||
if se.Reason != "reason" {
|
if se.Reason != "reason" {
|
||||||
t.Errorf("got %+v want %+v", se, err)
|
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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user