utils package provides utility functions for common tasks including gRPC error status handling.
Features
- gRPC Status Extraction: Extract status codes from errors
- Error Type Detection: Identify gRPC errors
- Status Text Conversion: Human-readable status strings
Installation
gRPC Status Utilities
The utils package provides helpers for working with gRPC status codes.StatusCode
codes.OK if error is nil, or codes.Unknown if the error doesn’t implement gRPC status.
Example:
StatusText
Status Code Mappings
The package includes mappings for all gRPC status codes:| Code | String |
|---|---|
codes.OK | "OK" |
codes.Canceled | "CANCELED" |
codes.Unknown | "UNKNOWN" |
codes.InvalidArgument | "INVALID_ARGUMENT" |
codes.DeadlineExceeded | "DEADLINE_EXCEEDED" |
codes.NotFound | "NOT_FOUND" |
codes.AlreadyExists | "ALREADY_EXISTS" |
codes.PermissionDenied | "PERMISSION_DENIED" |
codes.ResourceExhausted | "RESOURCE_EXHAUSTED" |
codes.FailedPrecondition | "FAILED_PRECONDITION" |
codes.Aborted | "ABORTED" |
codes.OutOfRange | "OUT_OF_RANGE" |
codes.Unimplemented | "UNIMPLEMENTED" |
codes.Internal | "INTERNAL" |
codes.Unavailable | "UNAVAILABLE" |
codes.DataLoss | "DATA_LOSS" |
codes.Unauthenticated | "UNAUTHENTICATED" |
Complete Example: gRPC Error Handling
HTTP Status Mapping
Common pattern for mapping gRPC codes to HTTP status codes:Middleware Example
Retry Logic Example
Circuit Breaker Pattern
Best Practices
Use Specific Error Codes
Use Specific Error Codes
Choose appropriate gRPC codes for different scenarios:
Handle All Error Cases
Handle All Error Cases
Use switch statements to handle different error types:
Log Error Context
Log Error Context
Include status codes in logs:
Implement Retry Logic
Implement Retry Logic
Retry only on appropriate error codes: