Exception: Typesafe::APIError

Inherits:
Error
  • Object
show all
Defined in:
lib/typesafe/errors.rb

Overview

A non-2xx HTTP response from the TypeSafe API.

begin
client.evaluate(state:, questions:)
rescue Typesafe::RateLimitError => e
sleep(e.retry_after || 1.0)
retry
end

The detail field of an error body comes in three shapes, all of which are rendered into the exception message:

  • a plain String — {"detail": "Unknown model: jev-99"}
  • a Hash with error_type/message — {"detail": {"error_type": "authentication_error", "message": "..."}}
  • an Array of validation entries (FastAPI/pydantic style) — {"detail": [{"type": "missing", "loc": ["body", "questions"], "msg": "Field required"}]}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(status:, body: nil, headers: {}, message: nil) ⇒ APIError

Returns a new instance of APIError.

Parameters:

  • status (Integer)

    the HTTP status code.

  • body (Hash, Array, String, nil) (defaults to: nil)

    the parsed or raw response body.

  • headers (Hash{String => String}) (defaults to: {})

    the response headers.

  • message (String, nil) (defaults to: nil)

    overrides the rendered +detail+-based message.



39
40
41
42
43
44
45
# File 'lib/typesafe/errors.rb', line 39

def initialize(status:, body: nil, headers: {}, message: nil)
  @status = status
  @body = body
  @headers = headers
  @request_id = header("x-typesafe-request-id")
  super(message || "The TypeSafe API returned status #{status}.")
end

Instance Attribute Details

#bodyHash, ... (readonly)

Returns the parsed JSON body (Hash or Array), the raw body String when it is not valid JSON, or nil for an empty body.

Returns:

  • (Hash, Array, String, nil)

    the parsed JSON body (Hash or Array), the raw body String when it is not valid JSON, or nil for an empty body.



29
30
31
# File 'lib/typesafe/errors.rb', line 29

def body
  @body
end

#headersHash{String => String} (readonly)

Returns the response headers, as received.

Returns:

  • (Hash{String => String})

    the response headers, as received.



31
32
33
# File 'lib/typesafe/errors.rb', line 31

def headers
  @headers
end

#request_idString? (readonly)

Returns the x-typesafe-request-id response header, when present.

Returns:

  • (String, nil)

    the x-typesafe-request-id response header, when present.



33
34
35
# File 'lib/typesafe/errors.rb', line 33

def request_id
  @request_id
end

#statusInteger (readonly)

Returns the HTTP status code.

Returns:

  • (Integer)

    the HTTP status code.



26
27
28
# File 'lib/typesafe/errors.rb', line 26

def status
  @status
end

Instance Method Details

#retryable?Boolean

True when the request may succeed if retried after a delay: rate limits (429), overload (529) and server errors (5xx).

Returns:

  • (Boolean)


50
51
52
# File 'lib/typesafe/errors.rb', line 50

def retryable?
  status == 429 || status == 529 || (500..599).cover?(status)
end