use thiserror::Error;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum NativeErrorCode {
Ok,
NotImplemented,
Internal,
InvalidArgument,
InvalidUsage,
OperationCancelled,
Network,
Unknown(i32),
}
#[derive(Debug, Error)]
pub enum FoundryLocalError {
#[error("native error ({code:?}): {message}")]
Native {
code: NativeErrorCode,
message: String,
},
#[error("library load error: {reason}")]
LibraryLoad { reason: String },
#[error("command execution error: {reason}")]
CommandExecution { reason: String },
#[error("invalid configuration: {reason}")]
InvalidConfiguration { reason: String },
#[error("model operation error: {reason}")]
ModelOperation { reason: String },
#[error("HTTP request error: {0}")]
HttpRequest(#[from] reqwest::Error),
#[error("serialization error: {0}")]
Serialization(#[from] serde_json::Error),
#[error("validation error: {reason}")]
Validation { reason: String },
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("internal error: {reason}")]
Internal { reason: String },
}
impl FoundryLocalError {
pub fn native_code(&self) -> Option<NativeErrorCode> {
match self {
Self::Native { code, .. } => Some(*code),
_ => None,
}
}
pub fn native_message(&self) -> Option<&str> {
match self {
Self::Native { message, .. } => Some(message),
_ => None,
}
}
}
pub type Result<T> = std::result::Result<T, FoundryLocalError>;
#[cfg(test)]
mod tests {
use super::{FoundryLocalError, NativeErrorCode};
#[test]
fn native_error_exposes_code_and_message() {
let error = FoundryLocalError::Native {
code: NativeErrorCode::Network,
message: "connection failed".into(),
};
assert_eq!(error.native_code(), Some(NativeErrorCode::Network));
assert_eq!(error.native_message(), Some("connection failed"));
}
#[test]
fn non_native_error_has_no_native_details() {
let error = FoundryLocalError::Validation {
reason: "invalid".into(),
};
assert_eq!(error.native_code(), None);
assert_eq!(error.native_message(), None);
}
}