grpc/grpc-go · error

invalid code: %q

Error message

invalid code: %q

What it means

In codes.Code.UnmarshalJSON (codes.go:245-249), if the JSON token is not a number and does not match any key in strToCode (the map of "OK","CANCELLED",…,"UNAUTHENTICATED"), it is rejected. The %q is the unrecognized string (including any surrounding quotes from the raw JSON).

Source

Thrown at codes/codes.go:249

	}
	if c == nil {
		return fmt.Errorf("nil receiver passed to UnmarshalJSON")
	}

	if ci, err := strconv.ParseUint(string(b), 10, 32); err == nil {
		if ci >= _maxCode {
			return fmt.Errorf("invalid code: %d", ci)
		}

		*c = Code(ci)
		return nil
	}

	if jc, ok := strToCode[string(b)]; ok {
		*c = jc
		return nil
	}
	return fmt.Errorf("invalid code: %q", string(b))
}

View on GitHub (pinned to 03255a9237)

Solutions

  1. Use the exact upper-snake-case name from the gRPC spec, e.g. "UNAVAILABLE".
  2. If the source uses different casing, normalize it to upper-snake-case before unmarshalling.
  3. Alternatively send the numeric value (0..16) which is also accepted.

Example fix

// before
json.Unmarshal([]byte(`"Unavailable"`), &c)
// after
json.Unmarshal([]byte(`"UNAVAILABLE"`), &c)
Defensive patterns

Strategy: validation

Validate before calling

// Normalize a code string to upper-snake-case and check it is known.
func normalizeCodeName(s string) (string, bool) {
    up := strings.ToUpper(strings.TrimSpace(s))
    known := map[string]bool{"OK":true,"CANCELLED":true,"UNKNOWN":true,"INVALID_ARGUMENT":true,"DEADLINE_EXCEEDED":true,"NOT_FOUND":true,"ALREADY_EXISTS":true,"PERMISSION_DENIED":true,"RESOURCE_EXHAUSTED":true,"FAILED_PRECONDITION":true,"ABORTED":true,"OUT_OF_RANGE":true,"UNIMPLEMENTED":true,"INTERNAL":true,"UNAVAILABLE":true,"DATA_LOSS":true,"UNAUTHENTICATED":true}
    return up, known[up]
}

Prevention

When it happens

Trigger: Decoding JSON whose code field is a string that isn't a known gRPC code name — typos like "Unavailable" (wrong case) or "FAILED", or a completely foreign value.

Common situations: Case mismatch (codes are upper-snake-case: "UNAVAILABLE"); a non-gRPC enum string; a legacy/vendored schema using different naming.

Related errors


AI-assisted analysis of grpc/grpc-go@03255a9237 (2026-08-07). Data as JSON: /api/errors/6ec3595a8a476f04. Report an issue: GitHub.