use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ErrorCode {
InvalidInput = 1001,
MissingParameter = 1002,
Cancelled = 1003,
Timeout = 1004,
NotImplemented = 1005,
UnsupportedConfig = 1006,
ToolNotFound = 2001,
ToolValidation = 2002,
ToolExecution = 2003,
ToolSandboxed = 2004,
PermissionDenied = 3001,
PathNotAllowed = 3002,
NetworkBlocked = 3003,
HttpClientError = 4001,
HttpServerError = 4002,
ApiUnauthorized = 4003,
ApiRateLimited = 4004,
ConnectionTimeout = 4005,
ConnectionFailed = 4006,
FileNotFound = 5001,
FileReadError = 5002,
FileWriteError = 5003,
FilePermission = 5004,
InvalidPath = 5005,
DiskFull = 5006,
SessionNotFound = 6001,
SessionExpired = 6002,
SessionCapReached = 6003,
TranscriptCorrupt = 6004,
ModelUnsupportedParam = 7001,
ContextWindowExceeded = 7002,
ModelParseError = 7003,
ModelEmptyResponse = 7004,
StreamAborted = 7005,
McpConnectFailed = 8001,
McpToolCallFailed = 8002,
McpOAuthFailed = 8003,
InternalInconsistency = 9001,
ChannelClosed = 9002,
Internal = 9999,
}
impl ErrorCode {
pub fn label(self) -> &'static str {
match self {
Self::InvalidInput => "invalid input",
Self::MissingParameter => "missing parameter",
Self::Cancelled => "cancelled",
Self::Timeout => "timeout",
Self::NotImplemented => "not implemented",
Self::UnsupportedConfig => "unsupported config",
Self::ToolNotFound => "tool not found",
Self::ToolValidation => "tool validation failed",
Self::ToolExecution => "tool execution failed",
Self::ToolSandboxed => "tool blocked by sandbox",
Self::PermissionDenied => "permission denied",
Self::PathNotAllowed => "path not allowed",
Self::NetworkBlocked => "network blocked by policy",
Self::HttpClientError => "HTTP client error",
Self::HttpServerError => "HTTP server error",
Self::ApiUnauthorized => "API unauthorized",
Self::ApiRateLimited => "API rate limited",
Self::ConnectionTimeout => "connection timeout",
Self::ConnectionFailed => "connection failed",
Self::FileNotFound => "file not found",
Self::FileReadError => "file read error",
Self::FileWriteError => "file write error",
Self::FilePermission => "file permission denied",
Self::InvalidPath => "invalid path",
Self::DiskFull => "disk full",
Self::SessionNotFound => "session not found",
Self::SessionExpired => "session expired",
Self::SessionCapReached => "session capacity reached",
Self::TranscriptCorrupt => "transcript corrupt",
Self::ModelUnsupportedParam => "model unsupported parameter",
Self::ContextWindowExceeded => "context window exceeded",
Self::ModelParseError => "model response parse error",
Self::ModelEmptyResponse => "model returned empty response",
Self::StreamAborted => "stream aborted",
Self::McpConnectFailed => "MCP connect failed",
Self::McpToolCallFailed => "MCP tool call failed",
Self::McpOAuthFailed => "MCP OAuth failed",
Self::InternalInconsistency => "internal state inconsistency",
Self::ChannelClosed => "channel closed",
Self::Internal => "internal error",
}
}
pub fn code(self) -> u16 {
self as u16
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[E{:04}] {}", self.code(), self.label())
}
}
#[derive(Debug)]
pub struct CodedError {
pub code: ErrorCode,
pub message: String,
pub source: Option<anyhow::Error>,
}
impl CodedError {
pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
source: None,
}
}
pub fn with_source(code: ErrorCode, message: impl Into<String>, source: anyhow::Error) -> Self {
Self {
code,
message: message.into(),
source: Some(source),
}
}
pub fn diagnostic(&self) -> String {
let mut s = format!("[E{:04}] {}", self.code.code(), self.message);
if let Some(ref src) = self.source {
s.push_str(&format!("\n caused by: {src}"));
}
s
}
}
impl fmt::Display for CodedError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[E{:04}] {}", self.code.code(), self.message)
}
}
impl std::error::Error for CodedError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source
.as_ref()
.map(|e| e.as_ref() as &dyn std::error::Error)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_code_has_label() {
let codes = &[
ErrorCode::InvalidInput,
ErrorCode::MissingParameter,
ErrorCode::Cancelled,
ErrorCode::Timeout,
ErrorCode::NotImplemented,
ErrorCode::UnsupportedConfig,
ErrorCode::ToolNotFound,
ErrorCode::ToolValidation,
ErrorCode::ToolExecution,
ErrorCode::ToolSandboxed,
ErrorCode::PermissionDenied,
ErrorCode::PathNotAllowed,
ErrorCode::NetworkBlocked,
ErrorCode::HttpClientError,
ErrorCode::HttpServerError,
ErrorCode::ApiUnauthorized,
ErrorCode::ApiRateLimited,
ErrorCode::ConnectionTimeout,
ErrorCode::ConnectionFailed,
ErrorCode::FileNotFound,
ErrorCode::FileReadError,
ErrorCode::FileWriteError,
ErrorCode::FilePermission,
ErrorCode::InvalidPath,
ErrorCode::DiskFull,
ErrorCode::SessionNotFound,
ErrorCode::SessionExpired,
ErrorCode::SessionCapReached,
ErrorCode::TranscriptCorrupt,
ErrorCode::ModelUnsupportedParam,
ErrorCode::ContextWindowExceeded,
ErrorCode::ModelParseError,
ErrorCode::ModelEmptyResponse,
ErrorCode::StreamAborted,
ErrorCode::McpConnectFailed,
ErrorCode::McpToolCallFailed,
ErrorCode::McpOAuthFailed,
ErrorCode::InternalInconsistency,
ErrorCode::ChannelClosed,
ErrorCode::Internal,
];
for &c in codes {
assert!(!c.label().is_empty(), "{c:?} missing label");
assert!(c.code() >= 1001, "{c:?} code out of range");
assert!(
format!("{c}").contains(&format!("E{:04}", c.code())),
"{c:?} Display format wrong"
);
}
assert!(
codes.len() >= 39,
"expected at least 39 codes, got {}",
codes.len()
);
}
#[test]
fn coded_error_display() {
let e = CodedError::new(ErrorCode::FileNotFound, "no such file: /tmp/x");
assert_eq!(e.to_string(), "[E5001] no such file: /tmp/x");
}
#[test]
fn coded_error_diagnostic_includes_source() {
let inner = anyhow::anyhow!("permission denied");
let e = CodedError::with_source(ErrorCode::FileReadError, "read failed", inner);
let diag = e.diagnostic();
assert!(diag.contains("E5002"));
assert!(diag.contains("read failed"));
assert!(diag.contains("permission denied"));
}
#[test]
fn coded_error_into_anyhow() {
let e = CodedError::new(ErrorCode::Timeout, "timed out");
let a: anyhow::Error = e.into();
assert!(a.to_string().contains("E1004"));
}
#[test]
fn error_code_prefixes_cover_all_categories() {
let all_codes = &[
ErrorCode::InvalidInput,
ErrorCode::ToolNotFound,
ErrorCode::PermissionDenied,
ErrorCode::HttpClientError,
ErrorCode::FileNotFound,
ErrorCode::SessionNotFound,
ErrorCode::ModelUnsupportedParam,
ErrorCode::McpConnectFailed,
ErrorCode::Internal,
];
let categories: std::collections::HashSet<u16> =
all_codes.iter().map(|c| c.code() / 1000).collect();
for cat in 1..=9 {
assert!(categories.contains(&cat), "missing error category {cat}xxx");
}
}
}