gRPC & High Performance APIs · Урок

Расширенные модели ошибок с google.rpc.Status

Выйдите за рамки обычных кодов состояния: добавляйте структурированные, понятные машинам сведения об ошибках с помощью модели google.rpc.Status и стандартных типов детализации ошибок.

Урок 4 из 413 шагов

«Расширенные модели ошибок с google.rpc.Status» — бесплатный урок gRPC & High Performance APIs на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения gRPC & High Performance APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс gRPC & High Performance APIs содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Limits of Plain Status Codes

A bare status code plus a message tells the client that something failed, but not the structured why. Clients often need field-level validation errors, retry hints, or quota info.

The rich error model attaches structured details to a status.

The google.rpc.Status Message

The core type is google.rpc.Status with three fields:

  • code: a numeric status code
  • message: developer-facing text
  • details: a repeated list of Any payloads

Standard Detail Types

Google defines reusable detail messages in google/rpc/error_details.proto:

  • BadRequest — field violations
  • RetryInfo — when to retry
  • QuotaFailure — limit exceeded
  • ErrorInfo — machine-readable reason

BadRequest for Validation

BadRequest carries a list of FieldViolation entries, each naming a bad field and describing the problem. Perfect for form validation responses.

Building a Rich Error in Go

The status package lets you create a status and append typed details with WithDetails.

st := status.New(codes.InvalidArgument, 'invalid request')
v := &errdetails.BadRequest_FieldViolation{
  Field: 'email', Description: 'must be a valid address',
}
br := &errdetails.BadRequest{FieldViolations: []*errdetails.BadRequest_FieldViolation{v}}
st, _ = st.WithDetails(br)
return st.Err()

RetryInfo for Backoff Hints

For temporary failures, attach RetryInfo with a retry_delay. A well-behaved client reads this and waits before retrying.

ri := &errdetails.RetryInfo{RetryDelay: durationpb.New(2 * time.Second)}
st, _ = status.New(codes.Unavailable, 'busy').WithDetails(ri)

ErrorInfo for Stable Reasons

ErrorInfo gives a stable reason string and a domain plus metadata. Unlike free-text messages, clients can branch on these reliably.

ei := &errdetails.ErrorInfo{
  Reason: 'EMAIL_TAKEN', Domain: 'auth.example.com',
}

Reading Details on the Client

The client converts the returned error back to a status and inspects each detail with a type switch.

st := status.Convert(err)
for _, d := range st.Details() {
  switch t := d.(type) {
  case *errdetails.BadRequest:
    handleFieldErrors(t)
  case *errdetails.RetryInfo:
    waitThenRetry(t.RetryDelay)
  }
}

How Details Travel

Details are serialized into the grpc-status-details-bin trailer as a binary Status proto. Languages with the rich-error libraries decode it automatically.

Best Practices

Use the rich model wisely:

  • Prefer standard detail types for interoperability
  • Never leak secrets in messages or details
  • Keep ErrorInfo.reason values stable and documented
  • Pair RetryInfo with truly retryable codes

Cross-Language Interop

Because the model is defined in protobuf, a Go server can emit a BadRequest that a Java or Python client decodes identically. This consistency is the whole point of the standard types.

Quick Check

Test your rich error knowledge.

Recap

You learned the rich error model:

  • google.rpc.Status carries code, message, and repeated detail Any payloads
  • Standard types: BadRequest, RetryInfo, QuotaFailure, ErrorInfo
  • Build with WithDetails, read with a type switch over Details()
  • Details travel in the grpc-status-details-bin trailer
  • Standard types give cross-language consistency
Можно начать бесплатно

Изучай gRPC & High Performance APIs с ИИ-репетитором — бесплатно

Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.

Курсы
12
Уроки
48

Часто задаваемые вопросы

Урок «Расширенные модели ошибок с google.rpc.Status» бесплатный?

Да — полный текст урока «Расширенные модели ошибок с google.rpc.Status» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс gRPC & High Performance APIs, подпишись на CoddyKit PRO. Курс gRPC & High Performance APIs содержит 4 уроков всего.

Чему я научусь в уроке «Расширенные модели ошибок с google.rpc.Status»?

Выйдите за рамки обычных кодов состояния: добавляйте структурированные, понятные машинам сведения об ошибках с помощью модели google.rpc.Status и стандартных типов детализации ошибок. Ты практикуешь gRPC & High Performance APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать gRPC & High Performance APIs?

Предыдущий опыт не требуется. gRPC & High Performance APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Расширенные модели ошибок с google.rpc.Status»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке gRPC & High Performance APIs?

Да. Каждый урок gRPC & High Performance APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Коды состояния и обработка ошибок
  2. Передача пользовательских метаданных
  3. Контекст и крайние сроки
  4. Расширенные модели ошибок с google.rpc.Status
← Назад к gRPC & High Performance APIs