use std::{error::Error as StdError, fmt};
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ErrorKind {
InvalidInput,
Unavailable,
Authentication,
RateLimited,
Capacity,
Timeout,
InputTooLarge,
EmptyOutput,
Protocol,
}
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
message: String,
}
impl Error {
pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
message: message.into(),
}
}
pub const fn kind(&self) -> ErrorKind {
self.kind
}
pub fn message(&self) -> &str {
&self.message
}
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.message)
}
}
impl StdError for Error {}
pub(crate) fn runtime(error: impl fmt::Display) -> Error {
Error::new(
ErrorKind::Unavailable,
clean_message(&error.to_string(), 500),
)
}
pub(crate) fn clean_message(value: &str, limit: usize) -> String {
let clean = value
.chars()
.map(|character| {
if character.is_control() {
' '
} else {
character
}
})
.take(limit)
.collect::<String>()
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
if clean.is_empty() {
"Codex operation failed".into()
} else {
clean
}
}