Skip to content

Handle API errors when the token has issues (invalid or low credits) #29

@ignacio-chiazzo

Description

@ignacio-chiazzo

Describe the bug
When the API token has issues, the gem raises a Faraday error. This can happen for several reasons, such as an invalid API token or low credit, etc.

To Reproduce

require 'bundler/inline'

gemfile(true) do
  source 'https://rubygems.org'

  git_source(:github) { |repo| "https://github.com/#{repo}.git" }

  gem "anthropic", path: "../"
end

require 'anthropic'


# secret key
client = Anthropic::Client.new(access_token: "invalid-key")

binding.pry
response = client.messages(
  parameters: {
    model: "claude-3-sonnet-20240229", 
    system: "Respond only in Spanish.",
    messages: [
      {"role": "user", "content": "Hello, Claude!"}
    ],
    max_tokens: 1000
  }
)

Expected behavior
A defined error is raised.

actual behavior
Faraday raises an error:

from (pry):3:in `on_complete'
gems/faraday-2.12.0/lib/faraday/response/raise_error.rb:31:in `on_complete': the server responded with status 400 (Faraday::BadRequestError)"
Screenshot 2024-10-09 at 4 36 05 PM

I inspected the API response and got the following error:

" @status=400 @reason_phrase="Bad Request" @response_body={"type"=>"error", "error"=>{"type"=>"invalid_request_error", "message"=>"Your credit balance is too low to access the Anthropic API. Please go to Plans & Billing to upgrade or purchase credits."}}>>

If you're okay with API consumers catching the API errors (4XX), I will close this issue and update the README. Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions