40.2 "Explain errors as JSON" for debuggability

Overview and links for this section of the guide.

Why Just JSON?

If the model returns an error, you want your code to handle it, not your user. If the model outputs "I'm sorry, I can't do that," your JSON parser crashes.

The Pattern

Force the model to always return JSON, even for errors.

type Response = {
  status: "success" | "error";
  data?: Payload;
  error?: {
    code: "RATE_LIMIT" | "INVALID_INPUT" | "UNSAFE";
    message: string;
    suggested_fix: string;
  };
}

This allows your UI to render a nice error toast: "Input unsafe: [message]" instead of crashing with `SyntaxError: Unexpected token I in JSON`.

Where to go next