grpc/grpc-go · error

invalid code: %d

Error message

invalid code: %d

What it means

In codes.Code.UnmarshalJSON (codes.go:236-238), if the JSON token parses as an unsigned integer but is >= _maxCode (17), it is out of the valid gRPC code range (0..16) and rejected. The %d is the offending numeric value.

Source

Thrown at codes/codes.go:238

	`"DATA_LOSS"`:           DataLoss,
	`"UNAUTHENTICATED"`:     Unauthenticated,
}

// UnmarshalJSON unmarshals b into the Code.
func (c *Code) UnmarshalJSON(b []byte) error {
	// From json.Unmarshaler: By convention, to approximate the behavior of
	// Unmarshal itself, Unmarshalers implement UnmarshalJSON([]byte("null")) as
	// a no-op.
	if string(b) == "null" {
		return nil
	}
	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 a valid code in 0..16 (see codes.Code constants: OK=0 … Unauthenticated=16).
  2. If the value comes from a third party, map/normalize it to a valid code before decoding.
  3. Send the code as its string name (e.g. "UNAVAILABLE") which is also accepted.

Example fix

// before
json.Unmarshal([]byte(`99`), &c)
// after
json.Unmarshal([]byte(`14`), &c)  // codes.Unavailable
Defensive patterns

Strategy: validation

Validate before calling

// Reject out-of-range numeric codes before decoding.
func validCodeNum(n uint64) bool { return n < 17 } // _maxCode

Type guard

func isValidCode(c codes.Code) bool { return int(c) >= 0 && int(c) < 17 }

Prevention

When it happens

Trigger: Decoding JSON containing a numeric status code >= 17 into a codes.Code — e.g. a hand-built status JSON, a proto JSON with a wrong numeric enum value, or a custom encoder emitting an unsupported code.

Common situations: An upstream service serialising a non-standard code number; test fixtures with made-up codes; a proto where the enum was extended beyond the gRPC spec.

Related errors


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