Catalog My learning Blog
gRPC and Protobuf Tutorial: Fast Microservice APIs · Phase 3 · Lesson 14 · 3 min read

gRPC Error Handling and Status Codes

On this page
  1. gRPC status codes and when to use each
  2. Returning gRPC errors in Go
  3. Rich error details with errdetails
  4. Propagating errors across services
  5. Check yourself

gRPC status codes and when to use each

HTTP has hundreds of status codes; gRPC has 17. Every call ends with one, plus a message and optional details. Because the set is small and shared across every language, clients can handle errors uniformly.

CodeUse whenClient should
OKSuccess
INVALID_ARGUMENTThe request is malformed whatever the system stateFix the request; don't retry
NOT_FOUNDThe requested entity doesn't existNot retry
ALREADY_EXISTSCreating something that existsNot retry
FAILED_PRECONDITIONSystem isn't in the right state (cancel a shipped order)Not retry until state changes
PERMISSION_DENIEDAuthenticated, not allowedNot retry
UNAUTHENTICATEDMissing or invalid credentialsRefresh credentials
RESOURCE_EXHAUSTEDQuota or rate limit, or message too largeBack off
ABORTEDConcurrency conflict (optimistic locking)Retry the whole transaction
UNAVAILABLETemporarily unavailableRetry with backoff (Day 22)
DEADLINE_EXCEEDEDDeadline passedMaybe retry, if idempotent
CANCELLEDThe caller cancelledNothing
UNIMPLEMENTEDMethod not implementedNot retry
INTERNALA bug or broken invariantNot retry blindly; investigate
UNKNOWNUnmapped error, often a raw error returned from a handlerInvestigate
DATA_LOSS, OUT_OF_RANGEUnrecoverable data loss; past the valid range

Common mistakes: returning plain errors (which become UNKNOWN), using INTERNAL for bad input, and UNAVAILABLE for permanent failures, which makes clients retry forever.

Returning gRPC errors in Go

Code
o, ok := s.orders[req.GetOrderId()]
if !ok {
	return nil, status.Errorf(codes.NotFound, "order %q not found", req.GetOrderId())
}

Rich error details with errdetails

A message string is for humans. For machines, attach error details: standard messages from google.rpc such as BadRequest (field violations), ErrorInfo (a reason and domain), RetryInfo (when to retry), QuotaFailure and PreconditionFailure.

Code
st := status.New(codes.InvalidArgument, "order_id is required")
st, _ = st.WithDetails(&errdetails.BadRequest{
	FieldViolations: []*errdetails.BadRequest_FieldViolation{
		{Field: "order_id", Description: "must not be empty"}}})
return nil, st.Err()

grpcurl shows the details travelling with the status:

YAML
ERROR:
  Code: InvalidArgument
  Message: order_id is required
  Details:
  1)	{
    	  "@type": "type.googleapis.com/google.rpc.BadRequest",
    	  "fieldViolations": [ { "field": "order_id", "description": "must not be empty" } ]
    	}

And the Go client reads them as typed values:

Code
st := status.Convert(err)
for _, d := range st.Details() {
	if br, ok := d.(*errdetails.BadRequest); ok {
		for _, v := range br.GetFieldViolations() {
			fmt.Printf("code=%s field=%s problem=%q\n", st.Code(), v.GetField(), v.GetDescription())
		}
	}
}
Code
error details:  code=InvalidArgument field=order_id problem="must not be empty"
Handlers return a status code, message and optional typed details; clients branch on the code and read details for field errors, retry timing or reasons.
Handlers return a status code, message and optional typed details; clients branch on the code and read details for field errors, retry timing or reasons.

Propagating errors across services

When service A calls B and B fails, don't forward B's status blindly: B's NOT_FOUND for an internal lookup might mean A has an INTERNAL bug, and B's INVALID_ARGUMENT means A built a bad request. Translate errors at each boundary, and never put internal details (stack traces, SQL) in messages that reach external callers.

Check yourself

INVALID_ARGUMENT means the request is wrong regardless of state; FAILED_PRECONDITION means the request is valid but the system isn't in a state that allows it.

Clients and retry policies treat UNAVAILABLE as transient and retry, wasting resources on both sides and delaying the caller learning about the real failure. Use a code that matches the cause, like NOT_FOUND or INVALID_ARGUMENT.

From typed details such as google.rpc.BadRequest attached to the status, which list each field violation with a description. Clients extract them with the status package instead of parsing messages.

Rarely as is. Map downstream errors to codes that make sense for your caller, for example a downstream NOT_FOUND may mean INTERNAL for you.

UNAUTHENTICATED means the caller's identity is missing or invalid, such as an expired token, so getting new credentials may help. PERMISSION_DENIED means the identity is known but not allowed to do this, so retrying with the same identity won't.