polyphony_types/schema/
apierror.rs

1#[cfg(feature = "poem")]
2use poem::{http::StatusCode, IntoResponse, Response};
3use serde_json::{json, Value};
4
5#[derive(Debug, thiserror::Error)]
6pub enum APIError {
7    #[error(transparent)]
8    Auth(#[from] AuthError),
9}
10
11impl APIError {
12    pub fn error_payload(&self) -> Value {
13        match self {
14            APIError::Auth(auth_err) => auth_err.error_payload(),
15        }
16    }
17}
18
19#[derive(Debug, thiserror::Error)]
20pub enum AuthError {
21    #[error("INVALID_LOGIN")]
22    InvalidLogin,
23    #[error("INVALID_CAPTCHA")]
24    InvalidCaptcha,
25}
26
27impl AuthError {
28    pub fn error_code(&self) -> &str {
29        match self {
30            AuthError::InvalidLogin => "INVALID_LOGIN",
31            AuthError::InvalidCaptcha => "INVALID_CATPCA",
32        }
33    }
34
35    pub fn error_payload(&self) -> Value {
36        match self {
37            AuthError::InvalidLogin => json!({
38                "login": {
39                    "message": "auth:login.INVALID_LOGIN",
40                    "code": self.error_code()
41                }
42            }),
43            AuthError::InvalidCaptcha => json!([json!({
44                "captcha_key": "TODO",
45                "captcha_sitekey": "TODO",
46                "captcha_service": "TODO"
47            })]),
48        }
49    }
50}
51
52#[cfg(feature = "poem")]
53impl poem::error::ResponseError for APIError {
54    fn status(&self) -> StatusCode {
55        match self {
56            APIError::Auth(auth_err) => match auth_err {
57                AuthError::InvalidLogin => StatusCode::UNAUTHORIZED,
58                AuthError::InvalidCaptcha => StatusCode::BAD_REQUEST,
59            },
60        }
61    }
62
63    fn as_response(&self) -> Response
64    where
65        Self: std::error::Error + Send + Sync + 'static,
66    {
67        Response::builder()
68            .status(self.status())
69            .body(self.error_payload().to_string())
70            .into_response()
71    }
72}