All files / src/providers/openai Errors.ts

78.26% Statements 18/23
82.6% Branches 19/23
50% Functions 1/2
81.81% Lines 18/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                    10x   10x   10x 10x 10x 10x 10x 10x                 10x   10x 2x     8x 3x     5x 3x     2x       2x 2x          
import {
  BadRequestError,
  AuthenticationError,
  RateLimitError,
  ServerError,
  ServiceUnavailableError,
  APIError
} from "../../errors/index.js";
 
export async function handleOpenAIError(response: Response, model?: string): Promise<never> {
  const status = response.status;
  let body: unknown;
  let message = `OpenAI 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 = `OpenAI error (${status}): ${body}`;
  }
 
  const provider = "openai";
 
  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);
  }
 
  Iif (status === 502 || status === 503) {
    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);
}