Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 39 ยท Error Handling and Metadata

Rich Error Details in gRPC

Go beyond a status code and message. Attach structured details such as BadRequest and RetryInfo to gRPC errors, and decode them on the client, with runnable Go stand-ins.

A status code and a message are enough for a log line, but not for a form. If a CreateUser call fails because three fields are wrong, the client wants to know which fields and why, in a form a program can read. Parsing English out of the message string is fragile and breaks the day someone fixes a typo.

gRPC solves this with the richer error model: a google.rpc.Status message with the code, the message and a list of details. Each detail is a protobuf message packed into an Any. Google publishes a set of standard detail types in google/rpc/error_details.proto, so every language agrees on their shape.

The real google.golang.org/grpc and genproto packages are not available on this site's runner. The go blocks outside a TryIt show the real API; the runnable blocks are stand-ins that model the same data flow with plain structs.

How the details travel

The detailed status is serialized and sent in a trailer called grpc-status-details-bin (the -bin suffix means the value is binary, base64 encoded on the wire). The ordinary grpc-status and grpc-message trailers are still sent, so old clients that ignore details keep working.

sequenceDiagram
    participant C as Client
    participant S as Server
    C->>S: CreateUser(name="", email="x")
    Note over S: validate request
    S-->>C: trailers:<br/>grpc-status: 3<br/>grpc-message: invalid user<br/>grpc-status-details-bin: Status{details:[BadRequest]}
    Note over C: decode details,<br/>highlight the wrong fields

The details ride in a trailer next to the plain code and message.

The standard detail types

Type Purpose
BadRequest A list of field violations (field path and description)
RetryInfo How long to wait before retrying
ErrorInfo A machine-readable reason, a domain and a metadata map
QuotaFailure Which quota was exceeded
PreconditionFailure Which precondition was not met
ResourceInfo The resource that was missing or in conflict
RequestInfo A request ID to quote in support tickets
Help Links to documentation
LocalizedMessage A message in a given locale, safe to show to users
DebugInfo Stack trace and hints (never send to untrusted clients)

ErrorInfo is the most useful for APIs. Its reason is a stable UPPER_SNAKE_CASE constant such as API_KEY_EXPIRED, which clients can switch on, while the message stays free to change.

Sending details from a Go server (real API)

Go
import (
    "google.golang.org/genproto/googleapis/rpc/errdetails"
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
)

func (s *server) CreateUser(ctx context.Context, req *pb.CreateUserRequest) (*pb.User, error) {
    br := &errdetails.BadRequest{}
    if req.GetName() == "" {
        br.FieldViolations = append(br.FieldViolations, &errdetails.BadRequest_FieldViolation{
            Field:       "name",
            Description: "must not be empty",
        })
    }
    if !strings.Contains(req.GetEmail(), "@") {
        br.FieldViolations = append(br.FieldViolations, &errdetails.BadRequest_FieldViolation{
            Field:       "email",
            Description: "must contain @",
        })
    }
    if len(br.FieldViolations) > 0 {
        st := status.New(codes.InvalidArgument, "invalid user")
        st, err := st.WithDetails(br)
        if err != nil {
            return nil, status.Error(codes.Internal, "could not attach details")
        }
        return nil, st.Err()
    }
    // ... create the user
}

WithDetails packs each message into an Any and returns a new status; statuses are immutable. It returns an error only if a detail cannot be marshaled.

Reading details on the client (real API)

Go
_, err := client.CreateUser(ctx, req)
if err != nil {
    st := status.Convert(err) // never nil, even for non-status errors
    for _, d := range st.Details() {
        switch info := d.(type) {
        case *errdetails.BadRequest:
            for _, v := range info.GetFieldViolations() {
                fmt.Printf("field %s: %s\n", v.GetField(), v.GetDescription())
            }
        case *errdetails.RetryInfo:
            fmt.Println("retry after", info.GetRetryDelay().AsDuration())
        }
    }
}

st.Details() returns []any: decoded messages for types the client knows and error values for types it cannot decode. That is why the type switch has no default that assumes success. Unknown detail types are simply skipped.

A runnable stand-in

The stand-in uses an interface for details, a status holding a slice of them and a type switch on the client, just like the real code.

Go Attach and decode error details

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Designing error reasons

Treat ErrorInfo.reason as part of your API contract. Good rules: a short constant, unique within the domain, never reworded once released, documented in the service reference. Put variable data in metadata ({"limit": "100"}), not in the reason. The message can then stay human-friendly and even be translated, while code branches on the reason.

Go Switch on reasons, not on messages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Practical advice

  • Validate everything first and return all field violations in one response, not one at a time.
  • Never include DebugInfo or stack traces for external clients. Log them on the server and send a RequestInfo with a request ID instead.
  • Keep messages for humans and details for programs.
  • Details are optional. A client that does not understand them still gets the code and message, so always make those useful.
  • In protobuf APIs, google.rpc.Status is also what you embed in a response message when an operation can partly fail (for example one status per item in a batch).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where do gRPC rich error details travel on the wire?

    The serialized google.rpc.Status is sent in the grpc-status-details-bin trailer, next to grpc-status and grpc-message.
  2. 2. Which standard detail type lists which request fields were invalid?

    BadRequest carries FieldViolation entries, each with a field path and a description.
  3. 3. Why should clients branch on ErrorInfo.reason instead of the status message?

    A reason is part of the API contract and does not change; messages are free text for humans.
  4. 4. What happens if a client does not know a detail type?

    Details are additive. Code and message always work, and unknown types are skipped or returned as decode errors.

Summary

  • The richer error model adds a list of typed details to the status code and message.
  • Standard types include BadRequest, ErrorInfo, RetryInfo, QuotaFailure, PreconditionFailure, ResourceInfo, RequestInfo, Help, LocalizedMessage and DebugInfo.
  • In Go use status.New(...).WithDetails(...) on the server and status.Convert(err).Details() on the client.
  • Return all validation problems at once, and keep ErrorInfo.reason stable.
  • Never leak debug information to untrusted callers.

Next: Metadata, Headers and Trailers