use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(clippy::large_enum_variant)] pub enum NRouterError {
Request(Box<ErrorBody>),
GuardrailBlocked(Box<ErrorBody>),
Authentication(Box<ErrorBody>),
Credit(Box<ErrorBody>),
BudgetExceeded(Box<ErrorBody>),
NotFound(Box<ErrorBody>),
RateLimit(Box<ErrorBody>),
Service(Box<ErrorBody>),
Other(Box<ErrorBody>),
Transport(String),
Configuration(String),
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ErrorBody {
pub message: String,
pub code: Option<String>,
pub status: Option<u16>,
pub request_id: Option<String>,
pub limit_source: Option<String>,
pub auth_reason: Option<String>,
pub retry_after: Option<u64>,
}
impl NRouterError {
pub fn from_code(body: ErrorBody) -> Self {
let boxed = Box::new(body);
let body = boxed;
match body.code.as_deref() {
Some("invalid_request") => Self::Request(body),
Some("guardrail_blocked") => Self::GuardrailBlocked(body),
Some("invalid_api_key") => Self::Authentication(body),
Some("insufficient_credits") => Self::Credit(body),
Some("model_not_found") => Self::NotFound(body),
Some("rate_limit_exceeded") | Some("tpm_limit_exceeded") => Self::RateLimit(body),
Some("credit_check_failed") | Some("service_unavailable") => Self::Service(body),
Some(_) => Self::Other(body),
None => match body.status {
Some(400) => {
if body.message.to_lowercase().contains("guardrail") {
Self::GuardrailBlocked(body)
} else {
Self::Request(body)
}
}
Some(401) => Self::Authentication(body),
Some(402) => {
if body
.message
.trim_start()
.to_lowercase()
.starts_with("budget")
{
Self::BudgetExceeded(body)
} else {
Self::Credit(body)
}
}
Some(404) => {
if body.message.to_lowercase().contains("model") {
Self::NotFound(body)
} else {
Self::Other(body)
}
}
Some(429) => Self::RateLimit(body),
Some(503) => Self::Service(body),
_ => Self::Other(body),
},
}
}
pub fn body(&self) -> Option<&ErrorBody> {
match self {
Self::Request(b)
| Self::GuardrailBlocked(b)
| Self::Authentication(b)
| Self::Credit(b)
| Self::BudgetExceeded(b)
| Self::NotFound(b)
| Self::RateLimit(b)
| Self::Service(b)
| Self::Other(b) => Some(b),
Self::Transport(_) | Self::Configuration(_) => None,
}
}
pub fn is_retryable(&self) -> bool {
matches!(
self,
Self::RateLimit(_) | Self::Service(_) | Self::Transport(_)
)
}
}
impl fmt::Display for NRouterError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Transport(m) => write!(f, "nRouter transport error: {m}"),
Self::Configuration(m) => write!(f, "nRouter configuration error: {m}"),
other => {
let b = other.body().expect("non-transport variants carry a body");
match &b.code {
Some(code) => write!(f, "{} ({code})", b.message),
None => write!(f, "{}", b.message),
}
}
}
}
}
impl std::error::Error for NRouterError {}