ClaudeAgentSDK.Errors (claude_agent_sdk v0.11.0)

Copy Markdown View Source

Structured error types for programmatic handling.

These mirror the Python SDK's exception taxonomy while keeping Elixir-friendly return shapes ({:error, reason} where reason is a struct).

Base Exception

ClaudeSDKError serves as the conceptual base for all SDK errors. While Elixir doesn't have exception inheritance, this provides a common pattern for wrapping lower-level errors with SDK-specific context.

Error Types

  • ClaudeSDKError - Base exception for generic SDK errors
  • CLIConnectionError - Connection/startup failures
  • CLINotFoundError - CLI executable not found
  • ProcessError - CLI process exited with error
  • CLIJSONDecodeError - JSON parsing failures
  • MessageParseError - Message structure parsing failures

Utility Functions

Guard Macro

Import ClaudeAgentSDK.Errors.Guards to use is_sdk_error/1 in guards:

import ClaudeAgentSDK.Errors.Guards

try do
  ClaudeAgentSDK.query("prompt", opts)
rescue
  e when is_sdk_error(e) ->
    Logger.error("SDK Error: #{Exception.message(e)}")
end

Examples

# Raising base SDK error
raise ClaudeAgentSDK.Errors.ClaudeSDKError, message: "Operation failed"

# Checking error type
Errors.sdk_error?(%Errors.CLIConnectionError{message: "failed"})
# => true

# Getting error category
Errors.category(%Errors.CLIConnectionError{message: "failed"})
# => :connection

Summary

Types

Error category for grouping related errors.

Union type of all SDK error types.

Functions

Get the category of an SDK error.

Check if an exception is an SDK error.

Types

category()

@type category() :: :connection | :process | :parse | :generic

Error category for grouping related errors.

sdk_error()

Union type of all SDK error types.

Functions

category(error)

@spec category(sdk_error()) :: category()

Get the category of an SDK error.

Categories help group related errors for handling:

  • :connection - Connection and CLI discovery errors
  • :process - CLI process execution errors
  • :parse - JSON and message parsing errors
  • :generic - Base SDK errors without specific category

Examples

iex> Errors.category(%Errors.CLIConnectionError{message: "failed"})
:connection

iex> Errors.category(%Errors.ProcessError{message: "crashed"})
:process

iex> Errors.category(%Errors.CLIJSONDecodeError{message: "bad", line: "{"})
:parse

sdk_error?(error)

@spec sdk_error?(term()) :: boolean()

Check if an exception is an SDK error.

Returns true if the given value is one of the SDK error types, false otherwise.

Examples

iex> Errors.sdk_error?(%Errors.ClaudeSDKError{message: "test"})
true

iex> Errors.sdk_error?(%Errors.CLIConnectionError{message: "failed"})
true

iex> Errors.sdk_error?(%RuntimeError{message: "not sdk"})
false

iex> Errors.sdk_error?("string")
false