Go Grpc Error Handling
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.
Right
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
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - 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
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