Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert gRPC error codes client side in Go

Tags:

go

grpc

Given the following gRPC server side code:

import (
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
    ....
)

....

func (s *Router) Assign(ctx context.Context, req *api.Request(*api.Response, error) {

    return nil, status.Errorf(codes.PermissionDenied,
}

....

What is the recommended technique for asserting client side that the error is of code = codes.PermissionDenied ?

like image 252
Myles McDonnell Avatar asked Oct 24 '18 12:10

Myles McDonnell


People also ask

How to handle error in gRPC?

If an error occurs, gRPC returns one of its error status codes instead, with an optional string error message that provides further details about what happened. Error information is available to gRPC clients in all supported languages.

What does IO gRPC 7 mean?

7. The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors).


1 Answers

Let's say your server returns codes.PermissionDenined like this

...
return nil, status.Error(codes.PermissionDenied, "PERMISSION_DENIED_TEXT")

If your client is Golang as well can also use the status library function FromError to parse the error. I use a switch to determine the error code returned like so

// client
    assignvar, err := s.MyFunctionCall(ctx, ...)
    if err != nil {
        if e, ok := status.FromError(err); ok {
            switch e.Code() {
            case codes.PermissionDenied:
                fmt.Println(e.Message()) // this will print PERMISSION_DENIED_TEST
            case codes.Internal:
                fmt.Println("Has Internal Error")
            case codes.Aborted:
                fmt.Println("gRPC Aborted the call")
            default:
                fmt.Println(e.Code(), e.Message())
            }
        }
        else {
            fmt.Printf("not able to parse error returned %v", err)
        }
    }
like image 123
Trevor V Avatar answered Sep 25 '22 16:09

Trevor V