Skip to content

Go Grpc Error Handling

DodaTech 1 min read

In this tutorial, you'll learn about grpc error handling: status codes. We cover key concepts, practical examples, and best practices.

gRPC error codes -- Return proper gRPC status codes from server and handle them on the client side.

The Problem

Using fmt.Errorf or errors.New in gRPC handlers produces Unknown status code. Use status.Errorf or status.Error for proper gRPC error semantics.

Wrong

if err := validate(req); err != nil {
    return nil, fmt.Errorf("invalid request: %w", err)
}

Output:

// Client receives status: Unknown. No way to distinguish error type.
if err := validate(req); err != nil {
    return nil, status.Errorf(codes.InvalidArgument,
        "invalid request: %v", err)
}
// Server: return status.Error(codes.NotFound, "user not found")
// Client:
resp, err := client.GetUser(ctx, req)
if err != nil {
    st := status.Convert(err)
    switch st.Code() {
    case codes.NotFound:
        // Handle not found
    case codes.InvalidArgument:
        // Handle bad request
    }
}

Output:

// Proper error codes propagate to client.

Prevention

  • Use status.Errorf(codes.XXX, msg) for server errors
  • Use status.Convert(err) on client side
  • Common codes: NotFound, InvalidArgument, Unauthenticated, Internal, Unavailable
  • Use codes.PermissionDenied for auth errors
  • Include details with status.WithDetails()

Common Mistakes with grpc error handling

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**What is the default error code?**

codes.Unknown. Always use explicit codes.

Can I include error details?

Yes. Use status.New(c, m).WithDetails(protoMsg).

How to return multiple errors?

Use status.New(c, m).WithDetails() with multiple detail protos.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro