Skip to main content

agentkernel_sdk/
error.rs

1/// Errors returned by the agentkernel SDK.
2#[derive(Debug, thiserror::Error)]
3pub enum Error {
4    /// 401 Unauthorized.
5    #[error("authentication error: {0}")]
6    Auth(String),
7
8    /// 404 Not Found.
9    #[error("not found: {0}")]
10    NotFound(String),
11
12    /// 400 Bad Request.
13    #[error("validation error: {0}")]
14    Validation(String),
15
16    /// 500 Internal Server Error.
17    #[error("server error: {0}")]
18    Server(String),
19
20    /// Network / connection error.
21    #[error("network error: {0}")]
22    Network(#[from] reqwest::Error),
23
24    /// SSE streaming error.
25    #[error("stream error: {0}")]
26    Stream(String),
27
28    /// JSON serialization/deserialization error.
29    #[error("json error: {0}")]
30    Json(#[from] serde_json::Error),
31}
32
33pub type Result<T> = std::result::Result<T, Error>;
34
35/// Map an HTTP status + body to the appropriate error variant.
36pub fn error_from_status(status: u16, body: &str) -> Error {
37    let message = serde_json::from_str::<serde_json::Value>(body)
38        .ok()
39        .and_then(|v| v.get("error").and_then(|e| e.as_str().map(String::from)))
40        .unwrap_or_else(|| body.to_string());
41
42    match status {
43        400 => Error::Validation(message),
44        401 => Error::Auth(message),
45        404 => Error::NotFound(message),
46        _ => Error::Server(message),
47    }
48}