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    /// Invalid JWT credentials: the JWT token is invalid or expired.
28    #[error("invalid jwt credentials: {0}")]
29    InvalidJWTCredentials(#[from] jsonwebtoken::errors::Error),
30    /// No JWT secret found: the JWT secret is not configured.
31    #[error("no jwt secret found")]
32    NoJWTSecretFound,
33}
34
35impl Error {
36    fn status(&self) -> u16 {
37        match self {
38            Error::AuthenticationError(_) | Error::InvalidJWTCredentials(_) => 401,
39            Error::HttpError(_)
40            | Error::Io(_)
41            | Error::PromptError(_)
42            | Error::RpcError(_)
43            | Error::ProviderError(_)
44            | Error::NoJWTSecretFound => 500,
45        }
46    }
47}
48
49/// API error type used for provider-specific error responses.
50#[derive(Debug, Deserialize, Serialize)]
51pub struct ApiError {
52    status: u16,
53    message: String,
54}
55
56impl Display for ApiError {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        write!(f, "{}: {}", self.status, self.message)
59    }
60}
61
62impl From<Error> for ApiError {
63    fn from(value: Error) -> Self {
64        Self {
65            status: value.status(),
66            message: value.to_string(),
67        }
68    }
69}
70
71impl std::error::Error for ApiError {}