Skip to content

Commit

Permalink
Use grpc/status package
Browse files Browse the repository at this point in the history
  • Loading branch information
avinassh committed Dec 18, 2017
1 parent 3faf519 commit 9bf84e0
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
11 changes: 6 additions & 5 deletions go/client.go
Expand Up @@ -6,9 +6,10 @@ import (

"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"

api "github.com/avinassh/grpc-errors/go/hello"
"google.golang.org/grpc/codes"
)

func main() {
Expand Down Expand Up @@ -36,16 +37,16 @@ func main() {
// ouch!
// lets print the gRPC error message
// which is "Length of `Name` cannot be more than 10 characters"
fmt.Println(grpc.ErrorDesc(err))
errStatus, _ := status.FromError(err)
fmt.Println(errStatus.Message())
// lets print the error code which is `INVALID_ARGUMENT`
status_code := grpc.Code(err)
fmt.Println(status_code)
fmt.Println(errStatus.Code())
// Want its int version for some reason?
// you shouldn't actullay do this, but if you need for debugging,
// you can do `int(status_code)` which will give you `3`
//
// Want to take specific action based on specific error?
if codes.InvalidArgument == status_code {
if codes.InvalidArgument == errStatus.Code() {
// do your stuff here
log.Fatal()
}
Expand Down
3 changes: 2 additions & 1 deletion go/server.go
Expand Up @@ -8,6 +8,7 @@ import (
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"

api "github.com/avinassh/grpc-errors/go/hello"
)
Expand All @@ -20,7 +21,7 @@ func (s *HelloServer) SayHello(ctx context.Context, req *api.HelloReq) (*api.Hel

func (s *HelloServer) SayHelloStrict(ctx context.Context, req *api.HelloReq) (*api.HelloResp, error) {
if len(req.GetName()) >= 10 {
return nil, grpc.Errorf(codes.InvalidArgument,
return nil, status.Errorf(codes.InvalidArgument,
"Length of `Name` cannot be more than 10 characters")
}

Expand Down

0 comments on commit 9bf84e0

Please sign in to comment.