export type ErrorType = | "invalid_request_error" | "authentication_error" | "rate_limit_error" | "not_found_error" | "server_error"; export class ApiError extends Error { constructor( public readonly statusCode: number, public readonly errorMessage: string, public readonly errorType: ErrorType, public readonly errorCode: string, public readonly param?: string | null, ) { super(errorMessage); this.name = "ApiError"; } toJSON() { return { error: { message: this.errorMessage, type: this.errorType, code: this.errorCode, param: this.param ?? null, }, }; } toResponse(): Response { return Response.json(this.toJSON(), { status: this.statusCode }); } } export function invalidApiKey(): ApiError { return new ApiError(401, "Invalid API key provided.", "authentication_error", "invalid_api_key"); } export function rateLimitExceeded(reason: string, retryAfter: number): Response { const error = new ApiError(429, reason, "rate_limit_error", "rate_limit_exceeded"); return new Response(JSON.stringify(error.toJSON()), { status: 429, headers: { "Content-Type": "application/json", "Retry-After": String(retryAfter), }, }); } export function modelNotFound(model: string): ApiError { return new ApiError( 404, `The model '${model}' does not exist or you do not have access to it.`, "not_found_error", "model_not_found", ); } export function invalidRequest(message: string, param?: string): ApiError { return new ApiError(400, message, "invalid_request_error", "invalid_request", param); } export function providerError(message: string): ApiError { return new ApiError(502, message, "server_error", "provider_error"); } export function internalError(message = "An internal error occurred."): ApiError { return new ApiError(500, message, "server_error", "internal_error"); }