All files / src/providers/anthropic Errors.ts

100% Statements 23/23
91.66% Branches 22/24
100% Functions 2/2
100% Lines 22/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                    8x   8x   8x 8x 7x 7x 7x 7x       1x 1x     8x   8x 2x     6x 2x     4x 1x     3x 1x     2x 1x     1x    
import {
  BadRequestError,
  AuthenticationError,
  RateLimitError,
  ServerError,
  ServiceUnavailableError,
  APIError
} from "../../errors/index.js";
 
export async function handleAnthropicError(response: Response, modelId: string): Promise<never> {
  const status = response.status;
  let body: unknown;
  let message = `Anthropic 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 {
    body = await response.text().catch(() => "Unknown error");
    message = `Anthropic error (${status}): ${body}`;
  }
 
  const provider = "anthropic";
 
  if (status === 400) {
    throw new BadRequestError(message, body, provider, modelId);
  }
 
  if (status === 401 || status === 403) {
    throw new AuthenticationError(message, status, body, provider);
  }
 
  if (status === 429) {
    throw new RateLimitError(message, body, provider, modelId);
  }
 
  if (status === 502 || status === 503 || status === 529) {
    throw new ServiceUnavailableError(message, status, body, provider, modelId);
  }
 
  if (status >= 500) {
    throw new ServerError(message, status, body, provider, modelId);
  }
 
  throw new APIError(message, status, body, provider, modelId);
}