package nstatus import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) //var table = map[codes.Code]int{ // codes.OK: code.StatusOK, // codes.Canceled: code.StatusRequestTimeout, // codes.Unknown: code.StatusInternalServerError, // codes.InvalidArgument: code.StatusBadRequest, // codes.DeadlineExceeded: code.StatusGatewayTimeout, // codes.NotFound: code.StatusNotFound, // codes.AlreadyExists: code.StatusConflict, // codes.PermissionDenied: code.StatusForbidden, // codes.ResourceExhausted: code.StatusTooManyRequests, // codes.FailedPrecondition: code.StatusBadRequest, // codes.Aborted: code.StatusConflict, // codes.OutOfRange: code.StatusBadRequest, // codes.Unimplemented: code.StatusNotImplemented, // codes.Internal: code.StatusInternalServerError, // codes.Unavailable: code.StatusServiceUnavailable, // codes.DataLoss: code.StatusInternalServerError, // codes.Unauthenticated: code.StatusUnauthorized, //} const GrpcResultTypeKey = "_RESULT_TYPE" // WrapGrpcErr 将grpc-error转换为 Result func WrapGrpcErr(err error) *Result { gErr := status.Convert(err) if gErr == nil { return nil } //if c, ok := table[gErr.Code()]; ok { // return NewResult(c, gErr.Message(), RpcErr) //} return NewResult(int(gErr.Code()), gErr.Message(), RpcErr) } // IsGrpcErr return an error if grpc status func IsGrpcErr(err error) bool { if err == nil { return false } _, ok := err.(interface { GRPCStatus() *status.Status }) return ok } /** RPC错误 */ func NewGrpcErr(code codes.Code, msg string) error { return NewResult(int(code), msg, RpcErr) } // NewGrpcInternalErr returns status error with Internal error code. func NewGrpcInternalErr(msg string) error { return NewGrpcErr(codes.Internal, msg) } // NewGrpcInvalidArgumentErr returns status error with InvalidArgument error code. func NewGrpcInvalidArgumentErr(msg string) error { return NewGrpcErr(codes.InvalidArgument, msg) } // NewGrpcNotFoundErr returns status error with NotFound error code. func NewGrpcNotFoundErr(msg string) error { return NewGrpcErr(codes.NotFound, msg) } // NewGrpcAlreadyExistsErr returns status error with AlreadyExists error code. func NewGrpcAlreadyExistsErr(msg string) error { return NewGrpcErr(codes.AlreadyExists, msg) } // NewGrpcUnauthenticatedErr returns status error with Unauthenticated error code. func NewGrpcUnauthenticatedErr(msg string) error { return NewGrpcErr(codes.Unauthenticated, msg) } // NewGrpcPermissionDeniedErr returns status error with PermissionDenied error code. func NewGrpcPermissionDeniedErr(msg string) error { return NewGrpcErr(codes.PermissionDenied, msg) }