Skip to main content

base/error/
mod.rs

1//! 通用错误类型 —— 跨 crate 边界的稳定错误。
2//! 各 crate 可以再定义自己的局部错误(thiserror)并通过 `#[from]` 转入这些。
3
4pub mod code;
5pub use code::{CodedError, ErrorCode};
6
7use std::time::Duration;
8
9impl ToolError {
10    /// Convenience: `Execution("...".into())`. Use `Execution(anyhow!(...))` in new code.
11    pub fn exec(msg: impl Into<String>) -> Self {
12        Self::Execution(anyhow::anyhow!("{}", msg.into()))
13    }
14}
15
16// Allow String to convert directly into ToolError::Execution.
17impl From<String> for ToolError {
18    fn from(s: String) -> Self {
19        Self::exec(s)
20    }
21}
22
23#[derive(thiserror::Error, Debug)]
24#[non_exhaustive]
25pub enum ToolError {
26    #[error("denied: {0}")]
27    Denied(String),
28
29    #[error("not found: {0}")]
30    NotFound(String),
31
32    #[error("input validation failed: {0}")]
33    Validation(String),
34
35    #[error("execution: {0}")]
36    Execution(#[source] anyhow::Error),
37
38    #[error("cancelled")]
39    Cancelled,
40
41    #[error("timeout after {0:?}")]
42    Timeout(Duration),
43
44    #[error("invalid input: {0}")]
45    InvalidInput(String),
46
47    #[error("io: {0}")]
48    Io(#[from] std::io::Error),
49
50    #[error("schema: {0}")]
51    Schema(#[from] serde_json::Error),
52
53    #[error("transport: {0}")]
54    Transport(#[source] anyhow::Error),
55}
56
57/// HTTP 响应状态码的语义枚举。
58///
59/// 覆盖常见的 4xx(客户端错误)和 5xx(服务端错误)。
60/// 通过 [`HttpError::from_status`] 按状态码构造。
61#[derive(thiserror::Error, Clone, Debug, PartialEq, Eq)]
62#[non_exhaustive]
63pub enum HttpError {
64    #[error("400 Bad Request")]
65    BadRequest,
66    #[error("401 Unauthorized")]
67    Unauthorized,
68    #[error("403 Forbidden")]
69    Forbidden,
70    #[error("404 Not Found")]
71    NotFound,
72    #[error("405 Method Not Allowed")]
73    MethodNotAllowed,
74    #[error("406 Not Acceptable")]
75    NotAcceptable,
76    #[error("408 Request Timeout")]
77    RequestTimeout,
78    #[error("409 Conflict")]
79    Conflict,
80    #[error("410 Gone")]
81    Gone,
82    #[error("413 Payload Too Large")]
83    PayloadTooLarge,
84    #[error("415 Unsupported Media Type")]
85    UnsupportedMediaType,
86    #[error("422 Unprocessable Entity")]
87    UnprocessableEntity,
88    #[error("429 Too Many Requests")]
89    TooManyRequests,
90
91    #[error("500 Internal Server Error")]
92    InternalServerError,
93    #[error("501 Not Implemented")]
94    NotImplemented,
95    #[error("502 Bad Gateway")]
96    BadGateway,
97    #[error("503 Service Unavailable")]
98    ServiceUnavailable,
99    #[error("504 Gateway Timeout")]
100    GatewayTimeout,
101    #[error("505 HTTP Version Not Supported")]
102    HttpVersionNotSupported,
103
104    /// 上述未列出的状态码(携带原始数值)。
105    #[error("HTTP {0}")]
106    Unknown(u16),
107}
108
109impl HttpError {
110    /// 从 HTTP 状态码构造对应的 [`HttpError`]。
111    ///
112    /// # Examples
113    ///
114    /// ```
115    /// # use base::error::HttpError;
116    /// assert!(matches!(HttpError::from_status(404), HttpError::NotFound));
117    /// assert!(matches!(HttpError::from_status(500), HttpError::InternalServerError));
118    /// assert!(matches!(HttpError::from_status(999), HttpError::Unknown(999)));
119    /// ```
120    pub fn from_status(code: u16) -> Self {
121        match code {
122            400 => Self::BadRequest,
123            401 => Self::Unauthorized,
124            403 => Self::Forbidden,
125            404 => Self::NotFound,
126            405 => Self::MethodNotAllowed,
127            406 => Self::NotAcceptable,
128            408 => Self::RequestTimeout,
129            409 => Self::Conflict,
130            410 => Self::Gone,
131            413 => Self::PayloadTooLarge,
132            415 => Self::UnsupportedMediaType,
133            422 => Self::UnprocessableEntity,
134            429 => Self::TooManyRequests,
135            500 => Self::InternalServerError,
136            501 => Self::NotImplemented,
137            502 => Self::BadGateway,
138            503 => Self::ServiceUnavailable,
139            504 => Self::GatewayTimeout,
140            505 => Self::HttpVersionNotSupported,
141            _ => Self::Unknown(code),
142        }
143    }
144}
145
146#[cfg(test)]
147mod http_error_tests {
148    use super::*;
149
150    #[test]
151    fn err() {
152        let e = HttpError::from_status(404);
153        assert!(matches!(e, HttpError::NotFound));
154    }
155
156    #[test]
157    fn all_4xx() {
158        let cases: &[(u16, HttpError)] = &[
159            (400, HttpError::BadRequest),
160            (401, HttpError::Unauthorized),
161            (403, HttpError::Forbidden),
162            (404, HttpError::NotFound),
163            (405, HttpError::MethodNotAllowed),
164            (406, HttpError::NotAcceptable),
165            (408, HttpError::RequestTimeout),
166            (409, HttpError::Conflict),
167            (410, HttpError::Gone),
168            (413, HttpError::PayloadTooLarge),
169            (415, HttpError::UnsupportedMediaType),
170            (422, HttpError::UnprocessableEntity),
171            (429, HttpError::TooManyRequests),
172        ];
173        for &(code, ref expected) in cases {
174            assert_eq!(
175                HttpError::from_status(code),
176                *expected,
177                "code {} did not match expected variant",
178                code,
179            );
180        }
181    }
182
183    #[test]
184    fn all_5xx() {
185        let cases: &[(u16, HttpError)] = &[
186            (500, HttpError::InternalServerError),
187            (501, HttpError::NotImplemented),
188            (502, HttpError::BadGateway),
189            (503, HttpError::ServiceUnavailable),
190            (504, HttpError::GatewayTimeout),
191            (505, HttpError::HttpVersionNotSupported),
192        ];
193        for &(code, ref expected) in cases {
194            assert_eq!(
195                HttpError::from_status(code),
196                *expected,
197                "code {} did not match expected variant",
198                code,
199            );
200        }
201    }
202
203    #[test]
204    fn unknown_code() {
205        assert!(matches!(
206            HttpError::from_status(418),
207            HttpError::Unknown(418)
208        ));
209        assert!(matches!(
210            HttpError::from_status(999),
211            HttpError::Unknown(999)
212        ));
213        assert!(matches!(HttpError::from_status(0), HttpError::Unknown(0)));
214    }
215
216    #[test]
217    fn display() {
218        assert_eq!(HttpError::NotFound.to_string(), "404 Not Found");
219        assert_eq!(
220            HttpError::InternalServerError.to_string(),
221            "500 Internal Server Error"
222        );
223        assert_eq!(HttpError::Unknown(418).to_string(), "HTTP 418");
224    }
225}
226
227#[derive(thiserror::Error, Debug)]
228#[non_exhaustive]
229pub enum ValidationError {
230    #[error("{message}")]
231    InvalidInput { message: String, code: i32 },
232
233    #[error("schema: {0}")]
234    Schema(#[from] serde_json::Error),
235}