All files / src/providers/gemini Errors.ts

82.6% Statements 19/23
87.5% Branches 21/24
50% Functions 1/2
86.36% Lines 19/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53                    5x   5x   5x 5x 5x 5x 5x 5x                 5x   5x 1x     4x 1x     3x 1x     2x 1x     1x 1x          
import {
  BadRequestError,
  AuthenticationError,
  RateLimitError,
  ServerError,
  ServiceUnavailableError,
  APIError
} from "../../errors/index.js";
 
export async function handleGeminiError(response: Response, model?: string): Promise<never> {
  const status = response.status;
  let body: unknown;
  let message = `Gemini error (${status})`;
 
  try {
    body = await response.json();
    Eif (body && typeof body === "object" && "error" in body) {
      const err = (body as { error: { message: string } }).error;
      Eif (err && err.message) {
        message = err.message;
      }
    }
  } catch {
    // If not JSON, use the status text
    body = await response.text().catch(() => "Unknown error");
    message = `Gemini error (${status}): ${body}`;
  }
 
  const provider = "gemini";
 
  if (status === 400) {
    throw new BadRequestError(message, body, provider, model);
  }
 
  if (status === 401 || status === 403) {
    throw new AuthenticationError(message, status, body, provider);
  }
 
  if (status === 429) {
    throw new RateLimitError(message, body, provider, model);
  }
 
  if (status === 502 || status === 503 || status === 504) {
    throw new ServiceUnavailableError(message, status, body, provider, model);
  }
 
  Eif (status >= 500) {
    throw new ServerError(message, status, body, provider, model);
  }
 
  throw new APIError(message, status, body, provider, model);
}