Skip to main content

rpc_agent/
error.rs

1use std::fmt::Display;
2
3use serde::{Deserialize, Serialize};
4use thiserror::Error;
5
6/// Error type used throughout the crate.
7#[derive(Error, Debug)]
8pub enum Error {
9    /// Provider error: the provider returned an error response.
10    #[error("provider error: {0}")]
11    ProviderError(String),
12    /// Authentication error: the provider returned an authentication error.
13    #[error("authentication error: {0}")]
14    AuthenticationError(String),
15    /// Client error: the HTTP client returned an error.
16    #[error("client error: {0}")]
17    HttpError(#[from] rig::http_client::Error),
18    /// Prompt error: the prompt returned an error.
19    #[error("prompt error: {0}")]
20    PromptError(#[from] rig::completion::PromptError),
21    /// IO error: an I/O error occurred.
22    #[error("io error: {0}")]
23    Io(#[from] std::io::Error),
24    /// RPC error: a remote procedure call error occurred.
25    #[error("rpc error: {0}")]
26    RpcError(#[from] tarpc::client::RpcError),
27}
28
29/// API error type used for provider-specific error responses.
30#[derive(Debug, Deserialize, Serialize)]
31pub struct ApiError {
32    status: u16,
33    message: String,
34}
35
36impl Display for ApiError {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        write!(f, "{}: {}", self.status, self.message)
39    }
40}
41
42impl From<Error> for ApiError {
43    fn from(value: Error) -> Self {
44        match value {
45            Error::ProviderError(e) => ApiError {
46                status: 500,
47                message: e,
48            },
49            Error::HttpError(error) => ApiError {
50                status: 500,
51                message: error.to_string(),
52            },
53            Error::PromptError(prompt_error) => ApiError {
54                status: 500,
55                message: prompt_error.to_string(),
56            },
57            Error::Io(error) => ApiError {
58                status: 500,
59                message: error.to_string(),
60            },
61            Error::AuthenticationError(e) => ApiError {
62                status: 401,
63                message: e,
64            },
65            Error::RpcError(server_error) => ApiError {
66                status: 500,
67                message: server_error.to_string(),
68            },
69        }
70    }
71}
72
73impl std::error::Error for ApiError {}