mirror of
https://github.com/go-kratos/kratos.git
synced 2025-01-26 03:52:12 +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:
parent
2024fa7cdb
commit
378d1ee3c7
@ -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…
x
Reference in New Issue
Block a user