use serde::{Deserialize, Serialize};
use thiserror::Error;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApiErrorBody {
#[serde(rename = "type")]
pub kind: String,
pub message: String,
}
#[derive(Debug, Error)]
pub enum Error {
#[error("Anthropic API error {kind} (status {status:?}): {message}")]
Api { status: Option<u16>, kind: String, message: String, request_id: Option<String> },
#[error("transport error: {0}")]
Transport(String),
#[error("could not decode the response: {0}")]
Decode(String),
#[error("deadline exceeded")]
Deadline,
#[error("invalid configuration: {0}")]
Config(String),
}
impl Error {
pub fn status(&self) -> Option<u16> {
match self {
Error::Api { status, .. } => *status,
_ => None,
}
}
pub fn is_retryable(&self) -> bool {
match self {
Error::Transport(_) => true,
Error::Api { status: Some(s), .. } => retryable_status(*s),
Error::Api { status: None, kind, .. } => matches!(kind.as_str(), "overloaded_error" | "api_error" | "rate_limit_error"),
_ => false,
}
}
}
pub(crate) fn retryable_status(status: u16) -> bool {
matches!(status, 408 | 409 | 429) || status >= 500
}