|  | 
|  | 1 | +//! Centralized error handling for eth2 API clients | 
|  | 2 | +//! | 
|  | 3 | +//! This module consolidates all error types, response processing, | 
|  | 4 | +//! and recovery logic for both beacon node and validator client APIs. | 
|  | 5 | +
 | 
|  | 6 | +use pretty_reqwest_error::PrettyReqwestError; | 
|  | 7 | +use reqwest::{Response, StatusCode}; | 
|  | 8 | +use sensitive_url::SensitiveUrl; | 
|  | 9 | +use serde::{Deserialize, Serialize}; | 
|  | 10 | +use std::{fmt, path::PathBuf}; | 
|  | 11 | + | 
|  | 12 | +/// Main error type for eth2 API clients | 
|  | 13 | +#[derive(Debug)] | 
|  | 14 | +pub enum Error { | 
|  | 15 | +    /// The `reqwest` client raised an error. | 
|  | 16 | +    HttpClient(PrettyReqwestError), | 
|  | 17 | +    /// The `reqwest_eventsource` client raised an error. | 
|  | 18 | +    SseClient(Box<reqwest_eventsource::Error>), | 
|  | 19 | +    /// The server returned an error message where the body was able to be parsed. | 
|  | 20 | +    ServerMessage(ErrorMessage), | 
|  | 21 | +    /// The server returned an error message with an array of errors. | 
|  | 22 | +    ServerIndexedMessage(IndexedErrorMessage), | 
|  | 23 | +    /// The server returned an error message where the body was unable to be parsed. | 
|  | 24 | +    StatusCode(StatusCode), | 
|  | 25 | +    /// The supplied URL is badly formatted. It should look something like `http://127.0.0.1:5052`. | 
|  | 26 | +    InvalidUrl(SensitiveUrl), | 
|  | 27 | +    /// The supplied validator client secret is invalid. | 
|  | 28 | +    InvalidSecret(String), | 
|  | 29 | +    /// The server returned a response with an invalid signature. It may be an impostor. | 
|  | 30 | +    InvalidSignatureHeader, | 
|  | 31 | +    /// The server returned a response without a signature header. It may be an impostor. | 
|  | 32 | +    MissingSignatureHeader, | 
|  | 33 | +    /// The server returned an invalid JSON response. | 
|  | 34 | +    InvalidJson(serde_json::Error), | 
|  | 35 | +    /// The server returned an invalid server-sent event. | 
|  | 36 | +    InvalidServerSentEvent(String), | 
|  | 37 | +    /// The server sent invalid response headers. | 
|  | 38 | +    InvalidHeaders(String), | 
|  | 39 | +    /// The server returned an invalid SSZ response. | 
|  | 40 | +    InvalidSsz(ssz::DecodeError), | 
|  | 41 | +    /// An I/O error occurred while loading an API token from disk. | 
|  | 42 | +    TokenReadError(PathBuf, std::io::Error), | 
|  | 43 | +    /// The client has been configured without a server pubkey, but requires one for this request. | 
|  | 44 | +    NoServerPubkey, | 
|  | 45 | +    /// The client has been configured without an API token, but requires one for this request. | 
|  | 46 | +    NoToken, | 
|  | 47 | +} | 
|  | 48 | + | 
|  | 49 | +/// An API error serializable to JSON. | 
|  | 50 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | 
|  | 51 | +pub struct ErrorMessage { | 
|  | 52 | +    pub code: u16, | 
|  | 53 | +    pub message: String, | 
|  | 54 | +    #[serde(default)] | 
|  | 55 | +    pub stacktraces: Vec<String>, | 
|  | 56 | +} | 
|  | 57 | + | 
|  | 58 | +/// An indexed API error serializable to JSON. | 
|  | 59 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | 
|  | 60 | +pub struct IndexedErrorMessage { | 
|  | 61 | +    pub code: u16, | 
|  | 62 | +    pub message: String, | 
|  | 63 | +    pub failures: Vec<Failure>, | 
|  | 64 | +} | 
|  | 65 | + | 
|  | 66 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | 
|  | 67 | +pub struct Failure { | 
|  | 68 | +    pub index: u64, | 
|  | 69 | +    pub message: String, | 
|  | 70 | +} | 
|  | 71 | + | 
|  | 72 | +impl Failure { | 
|  | 73 | +    pub fn new(index: usize, message: String) -> Self { | 
|  | 74 | +        Self { | 
|  | 75 | +            index: index as u64, | 
|  | 76 | +            message, | 
|  | 77 | +        } | 
|  | 78 | +    } | 
|  | 79 | +} | 
|  | 80 | + | 
|  | 81 | +/// Server error response variants | 
|  | 82 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | 
|  | 83 | +#[serde(untagged)] | 
|  | 84 | +pub enum ResponseError { | 
|  | 85 | +    Indexed(IndexedErrorMessage), | 
|  | 86 | +    Message(ErrorMessage), | 
|  | 87 | +} | 
|  | 88 | + | 
|  | 89 | +impl Error { | 
|  | 90 | +    /// If the error has a HTTP status code, return it. | 
|  | 91 | +    pub fn status(&self) -> Option<StatusCode> { | 
|  | 92 | +        match self { | 
|  | 93 | +            Error::HttpClient(error) => error.inner().status(), | 
|  | 94 | +            Error::SseClient(error) => { | 
|  | 95 | +                if let reqwest_eventsource::Error::InvalidStatusCode(status, _) = error.as_ref() { | 
|  | 96 | +                    Some(*status) | 
|  | 97 | +                } else { | 
|  | 98 | +                    None | 
|  | 99 | +                } | 
|  | 100 | +            } | 
|  | 101 | +            Error::ServerMessage(msg) => StatusCode::try_from(msg.code).ok(), | 
|  | 102 | +            Error::ServerIndexedMessage(msg) => StatusCode::try_from(msg.code).ok(), | 
|  | 103 | +            Error::StatusCode(status) => Some(*status), | 
|  | 104 | +            Error::InvalidUrl(_) => None, | 
|  | 105 | +            Error::InvalidSecret(_) => None, | 
|  | 106 | +            Error::InvalidSignatureHeader => None, | 
|  | 107 | +            Error::MissingSignatureHeader => None, | 
|  | 108 | +            Error::InvalidJson(_) => None, | 
|  | 109 | +            Error::InvalidSsz(_) => None, | 
|  | 110 | +            Error::InvalidServerSentEvent(_) => None, | 
|  | 111 | +            Error::InvalidHeaders(_) => None, | 
|  | 112 | +            Error::TokenReadError(..) => None, | 
|  | 113 | +            Error::NoServerPubkey | Error::NoToken => None, | 
|  | 114 | +        } | 
|  | 115 | +    } | 
|  | 116 | +} | 
|  | 117 | + | 
|  | 118 | +impl From<reqwest::Error> for Error { | 
|  | 119 | +    fn from(error: reqwest::Error) -> Self { | 
|  | 120 | +        Error::HttpClient(error.into()) | 
|  | 121 | +    } | 
|  | 122 | +} | 
|  | 123 | + | 
|  | 124 | +impl fmt::Display for Error { | 
|  | 125 | +    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | 
|  | 126 | +        write!(f, "{:?}", self) | 
|  | 127 | +    } | 
|  | 128 | +} | 
|  | 129 | + | 
|  | 130 | +/// Returns `Ok(response)` if the response is a `200 OK`, `202 ACCEPTED`, or `204 NO_CONTENT` | 
|  | 131 | +/// Otherwise, creates an appropriate error message. | 
|  | 132 | +pub async fn ok_or_error(response: Response) -> Result<Response, Error> { | 
|  | 133 | +    let status = response.status(); | 
|  | 134 | + | 
|  | 135 | +    if status == StatusCode::OK | 
|  | 136 | +        || status == StatusCode::ACCEPTED | 
|  | 137 | +        || status == StatusCode::NO_CONTENT | 
|  | 138 | +    { | 
|  | 139 | +        Ok(response) | 
|  | 140 | +    } else if let Ok(message) = response.json::<ResponseError>().await { | 
|  | 141 | +        match message { | 
|  | 142 | +            ResponseError::Message(message) => Err(Error::ServerMessage(message)), | 
|  | 143 | +            ResponseError::Indexed(indexed) => Err(Error::ServerIndexedMessage(indexed)), | 
|  | 144 | +        } | 
|  | 145 | +    } else { | 
|  | 146 | +        Err(Error::StatusCode(status)) | 
|  | 147 | +    } | 
|  | 148 | +} | 
|  | 149 | + | 
|  | 150 | +/// Returns `Ok(response)` if the response is a success (2xx) response. Otherwise, creates an | 
|  | 151 | +/// appropriate error message. | 
|  | 152 | +pub async fn success_or_error(response: Response) -> Result<Response, Error> { | 
|  | 153 | +    let status = response.status(); | 
|  | 154 | + | 
|  | 155 | +    if status.is_success() { | 
|  | 156 | +        Ok(response) | 
|  | 157 | +    } else if let Ok(message) = response.json().await { | 
|  | 158 | +        match message { | 
|  | 159 | +            ResponseError::Message(message) => Err(Error::ServerMessage(message)), | 
|  | 160 | +            ResponseError::Indexed(indexed) => Err(Error::ServerIndexedMessage(indexed)), | 
|  | 161 | +        } | 
|  | 162 | +    } else { | 
|  | 163 | +        Err(Error::StatusCode(status)) | 
|  | 164 | +    } | 
|  | 165 | +} | 
0 commit comments