Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 39 ยท Error Handling and Metadata

gRPC Status Codes

Learn the 17 gRPC status codes, when to return each one, how they map to HTTP, and which are safe to retry, with runnable Go stand-ins and real grpc-go code.

Every gRPC call ends with a status: a numeric code plus an optional human-readable message. There is no separate "success flag" and "exception" like in many HTTP APIs. A call that worked ends with status OK (code 0); every other code means something went wrong, and the code tells the caller what kind of wrong.

This matters because callers write logic against codes, not messages. A client decides to retry on UNAVAILABLE, to refresh a token on UNAUTHENTICATED and to show a form error on INVALID_ARGUMENT. If your server returns UNKNOWN for everything, nobody can write sensible logic. This lesson walks through the codes, how to pick the right one and how to use them in Go.

The real gRPC libraries (google.golang.org/grpc) cannot run in the browser or on this site's runner. The code in go blocks marked read-only is the real API. The runnable examples use a tiny stand-in with the same shape so you can experiment with the ideas.

The status codes

gRPC defines 17 codes. The numbers are part of the wire protocol (they travel in the grpc-status trailer), so they never change.

Code Name Use it when
0 OK The call succeeded
1 CANCELLED The caller cancelled the call
2 UNKNOWN You really cannot classify the error
3 INVALID_ARGUMENT The request is malformed, whatever the server state
4 DEADLINE_EXCEEDED The deadline passed before the call finished
5 NOT_FOUND A requested entity does not exist
6 ALREADY_EXISTS The entity you tried to create exists
7 PERMISSION_DENIED The caller is known but not allowed
8 RESOURCE_EXHAUSTED Quota, rate limit or out of memory or disk
9 FAILED_PRECONDITION The system is not in the state the operation needs
10 ABORTED A concurrency conflict (transaction, version check)
11 OUT_OF_RANGE A value is valid in type but outside the allowed range
12 UNIMPLEMENTED The method is not supported or not implemented
13 INTERNAL A bug or broken invariant on the server
14 UNAVAILABLE The service is temporarily unreachable; retry may help
15 DATA_LOSS Unrecoverable data corruption
16 UNAUTHENTICATED No valid credentials were supplied
flowchart TD
    A["Call failed"] --> B{"Is the request itself wrong?"}
    B -->|"Yes, any state"| C["INVALID_ARGUMENT / OUT_OF_RANGE"]
    B -->|"No"| D{"Credentials problem?"}
    D -->|"Missing or invalid"| E["UNAUTHENTICATED"]
    D -->|"Valid but not allowed"| F["PERMISSION_DENIED"]
    D -->|"No"| G{"Entity problem?"}
    G -->|"Missing"| H["NOT_FOUND"]
    G -->|"Already there"| I["ALREADY_EXISTS"]
    G -->|"No"| J{"Temporary?"}
    J -->|"Yes"| K["UNAVAILABLE / RESOURCE_EXHAUSTED"]
    J -->|"No"| L["FAILED_PRECONDITION / INTERNAL"]

A quick way to choose: start with "is the request wrong?" and work down.

Commonly confused pairs

INVALID_ARGUMENT vs FAILED_PRECONDITION. INVALID_ARGUMENT is about the request alone: an email without an @. It would fail no matter what the server holds. FAILED_PRECONDITION depends on state: "delete this folder" fails because the folder is not empty, but it would succeed once you empty it.

UNAUTHENTICATED vs PERMISSION_DENIED. The first means "I do not know who you are" (missing or expired token). The second means "I know who you are and the answer is no". Refreshing a token fixes the first; it never fixes the second.

ABORTED vs FAILED_PRECONDITION. ABORTED says "someone else got there first, try the whole read-modify-write again". It fits an optimistic-locking conflict.

NOT_FOUND and security. If revealing that a resource exists would leak information, return NOT_FOUND even when the real reason is a permission problem.

Which codes are safe to retry?

  • UNAVAILABLE: yes, usually with backoff. It is the canonical "try again" code.
  • DEADLINE_EXCEEDED: only if the operation is idempotent and you still have time budget.
  • ABORTED: retry at a higher level (re-read, then write again), not the same request blindly.
  • RESOURCE_EXHAUSTED: retry only after the delay the server asks for.
  • Everything else: no. The same request will fail the same way.

The next lessons build on this: rich error details and retries.

Status codes in Go (real API)

In grpc-go you return a status error from a handler with status.Error or status.Errorf, and read it on the client with status.FromError:

Go
import (
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
)

// Server
func (s *server) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.User, error) {
    if req.GetId() == "" {
        return nil, status.Error(codes.InvalidArgument, "id is required")
    }
    u, ok := s.users[req.GetId()]
    if !ok {
        return nil, status.Errorf(codes.NotFound, "user %q not found", req.GetId())
    }
    return u, nil
}

// Client
u, err := client.GetUser(ctx, &pb.GetUserRequest{Id: "42"})
if err != nil {
    st, _ := status.FromError(err)
    switch st.Code() {
    case codes.NotFound:
        // show "no such user"
    case codes.Unavailable:
        // retry later
    default:
        log.Printf("rpc failed: %v: %s", st.Code(), st.Message())
    }
}

Returning a plain errors.New("boom") from a handler gives the client code UNKNOWN. Always wrap errors in a status. Context errors are special: if your handler returns context.Canceled or context.DeadlineExceeded, grpc-go converts them to CANCELLED and DEADLINE_EXCEEDED.

A runnable stand-in

This stand-in models a status as a code plus a message, with a function that classifies a domain error into a code. It prints the numeric value and name, like gRPC logs do.

Go Mapping domain errors to status codes

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.

Notice that the default branch returns UNKNOWN. In a real service, prefer INTERNAL for bugs you know are yours, and keep UNKNOWN for errors that came from somewhere you cannot classify.

Mapping to HTTP

When you expose gRPC through a REST gateway (see REST transcoding), codes map to HTTP statuses. The mapping is fixed by convention:

Go gRPC code to HTTP status table

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.

Common mistakes

  • Returning INTERNAL for user mistakes. It pages your on-call engineer for nothing.
  • Putting secrets or stack traces in the message. The message goes to the client.
  • Using NOT_FOUND for "list returned no rows". An empty list is a successful OK with zero items.
  • Creating new meanings for codes. Use error details for extra structure instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A client sends an expired token. Which code should the server return?

    The caller has no valid identity, which is UNAUTHENTICATED. PERMISSION_DENIED is for a known caller who is not allowed.
  2. 2. Which code is the standard signal that a retry with backoff may succeed?

    UNAVAILABLE means the service is temporarily unreachable. The others fail identically on every retry.
  3. 3. You delete a folder that still contains files. The operation would work if the folder were empty. Which code fits best?

    The request is well formed, but the system state does not allow it yet. That is FAILED_PRECONDITION.
  4. 4. What status does a client see if a Go handler returns a plain errors.New("boom")?

    grpc-go wraps non-status errors as UNKNOWN. Wrap errors with status.Error to choose a precise code.

Summary

  • A gRPC call always ends with a status: a code from 17 fixed values plus an optional message.
  • Choose the code that tells the caller what to do next: fix the request, log in, retry or give up.
  • INVALID_ARGUMENT is state independent; FAILED_PRECONDITION depends on state.
  • UNAVAILABLE is the main retryable code; most others never succeed on retry.
  • In grpc-go use status.Error(codes.X, msg) on the server and status.FromError on the client.
  • Do not leak internal details in messages.

Next: Rich Error Details