AI / Google Antigravity Gemini Fundamentals Interview Questions
How do you handle Gemini API errors and implement robust error handling?
The Gemini API returns standard HTTP error codes. The Python SDK wraps these as typed exceptions from google.api_core.exceptions. Robust applications should handle these systematically with appropriate retry and fallback strategies.
import time from google import genai from google.api_core import exceptions as google_exceptions client = genai.Client() def gemini_call_with_retry(prompt: str, model: str = "gemini-3.5-flash", max_retries: int = 5) -> str: for attempt in range(max_retries): try: response = client.models.generate_content( model=model, contents=prompt, ) # Check if blocked by safety filters: if not response.candidates: reason = response.prompt_feedback.block_reason raise ValueError(f"Response blocked: {reason}") return response.text except google_exceptions.ResourceExhausted: # 429 rate limit wait = (2 ** attempt) + 0.1 print(f"Rate limited. Waiting {wait:.1f}s...") time.sleep(wait) except google_exceptions.InvalidArgument as e: # 400 bad request if "context window" in str(e).lower(): raise ValueError("Prompt too long - reduce size.") from e raise # Re-raise other bad request errors except google_exceptions.PermissionDenied: # 403 raise PermissionError("Invalid API key or insufficient permissions.") except google_exceptions.ServiceUnavailable: # 503 wait = 5 * (attempt + 1) print(f"Service unavailable. Waiting {wait}s...") time.sleep(wait) except google_exceptions.NotFound: # 404 raise ValueError(f"Model {model!r} not found or deprecated.") raise Exception(f"Max retries ({max_retries}) exceeded.")
| Exception | HTTP code | Common cause |
|---|---|---|
| ResourceExhausted | 429 | Rate limit hit - implement backoff |
| InvalidArgument | 400 | Bad parameters, context overflow |
| PermissionDenied | 403 | Invalid API key or unauthorised model |
| NotFound | 404 | Model deprecated or doesn't exist |
| ServiceUnavailable | 503 | Transient server error - retry |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
