How to Handle Errors in gRPC with Go

Handle gRPC errors in Go by checking the error return value and using status.FromError to extract the code and message.

Handle gRPC errors in Go by checking the error return value from client calls and using status.FromError to extract the error code and message.

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

_, err := client.MyMethod(ctx, req)
if err != nil {
	st, ok := status.FromError(err)
	if ok {
		// Handle specific gRPC error codes
		if st.Code() == codes.NotFound {
			log.Println("Resource not found")
		}
		log.Printf("gRPC error: %v - %s", st.Code(), st.Message())
	} else {
		// Handle non-gRPC errors (e.g., network issues)
		log.Printf("Non-gRPC error: %v", err)
	}
}