Braintrust.Error (Braintrust v0.3.0)

View Source

Error struct for Braintrust API errors.

All API functions return {:error, %Braintrust.Error{}} on failure, allowing pattern matching on the :type field.

Error Types

TypeHTTP StatusRetryable?Description
:bad_request400NoInvalid request parameters
:authentication401NoMissing or invalid API key
:permission_denied403NoInsufficient permissions
:not_found404NoResource not found
:conflict409YesConflict error
:unprocessable_entity422NoValidation error
:rate_limit429YesRate limit exceeded
:server_error5xxYesServer error
:timeoutN/AYesRequest timeout
:connectionN/AYesNetwork/connection error

Examples

case Braintrust.Project.get("invalid-id") do
  {:ok, project} ->
    handle_project(project)

  {:error, %Braintrust.Error{type: :not_found}} ->
    handle_not_found()

  {:error, %Braintrust.Error{type: :rate_limit, retry_after: ms}} ->
    Process.sleep(ms)
    retry()

  {:error, %Braintrust.Error{} = error} ->
    Logger.error("API error: #{error.message}")
end

Summary

Functions

Creates a new error struct.

Returns whether the error is retryable.

Converts an HTTP status code to an error type.

Types

error_type()

@type error_type() ::
  :bad_request
  | :authentication
  | :permission_denied
  | :not_found
  | :conflict
  | :unprocessable_entity
  | :rate_limit
  | :server_error
  | :timeout
  | :connection

t()

@type t() :: %Braintrust.Error{
  code: String.t() | nil,
  message: String.t(),
  retry_after: pos_integer() | nil,
  status: pos_integer() | nil,
  type: error_type()
}

Functions

new(type, message, opts \\ [])

@spec new(error_type(), String.t(), keyword()) :: t()

Creates a new error struct.

Examples

iex> error = Braintrust.Error.new(:not_found, "Project not found")
iex> error.type
:not_found
iex> error.message
"Project not found"

iex> error = Braintrust.Error.new(:rate_limit, "Too many requests", retry_after: 5000)
iex> error.retry_after
5000

retryable?(error)

@spec retryable?(t()) :: boolean()

Returns whether the error is retryable.

Retryable errors are those that may succeed on retry:

  • :conflict - Temporary conflict
  • :rate_limit - Rate limit will reset
  • :server_error - Server may recover
  • :timeout - Network may recover
  • :connection - Connection may be restored

Examples

iex> error = Braintrust.Error.new(:rate_limit, "Too many requests")
iex> Braintrust.Error.retryable?(error)
true

iex> error = Braintrust.Error.new(:not_found, "Resource not found")
iex> Braintrust.Error.retryable?(error)
false

type_from_status(status)

@spec type_from_status(pos_integer()) :: error_type()

Converts an HTTP status code to an error type.

Examples

iex> Braintrust.Error.type_from_status(404)
:not_found

iex> Braintrust.Error.type_from_status(500)
:server_error

iex> Braintrust.Error.type_from_status(503)
:server_error