notionrs/error/
mod.rs

1#![deny(missing_docs)]
2
3//! Errors that can happen when using notionrs
4
5/// Errors that can happen when using notionrs
6#[derive(thiserror::Error, Debug)]
7pub enum Error {
8    /// This error occurs when the request fails due to a network issue.
9    #[error("Network error: {0}")]
10    Network(String),
11
12    /// This error occurs when parsing the HTTP body fails.
13    #[error("HTTP body parse error: {0}")]
14    BodyParse(String),
15
16    /// This error occurs when the HTTP response has a non-200 status code.
17    #[error("HTTP error {status}: {message}")]
18    Http {
19        /// HTTP status code (e.g. 404)
20        status: u16,
21        /// Error message
22        message: String,
23    },
24
25    /// This library follows the Builder pattern, allowing requests to be sent even with missing parameters.
26    /// If request parameters are insufficient, this error will be returned.
27    ///
28    /// If invalid parameters are passed, the Notion API will return a 400 Bad Request error -> `Error::Http`.
29    #[error("Notion request parameter error: {0}")]
30    RequestParameter(String),
31
32    /// This error occurs when serialization or deserialization fails.
33    #[error("Serialization/Deserialization error: {0}")]
34    Serde(#[from] serde_json::Error),
35}
36
37/// Error response from the Notion API
38#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
39pub struct ErrorResponse {
40    /// always "error"
41    pub object: String,
42
43    /// HTTP Status Code ( `4xx` or `5xx` )
44    pub status: u16,
45
46    /// Error code
47    pub code: String,
48
49    /// Error details
50    pub message: String,
51
52    /// Request identifier
53    pub request_id: Option<String>,
54
55    /// URL for the developer survey
56    pub developer_survey: Option<String>,
57}
58
59impl Error {
60    pub(crate) async fn try_from_response_async(response: reqwest::Response) -> Self {
61        let status = response.status().as_u16();
62
63        let error_body = match response.text().await{
64            Err(_) =>{
65                return crate::error::Error::Http {
66                    status,
67                    message: "An error occurred, but failed to retrieve the error details from the response body.".to_string(),
68                }},
69            Ok(body) => body
70        };
71
72        let error_json = serde_json::from_str::<crate::error::ErrorResponse>(&error_body).ok();
73
74        let error_message = match error_json {
75            Some(e) => e.message,
76            None => format!("{:?}", error_body),
77        };
78
79        crate::error::Error::Http {
80            status,
81            message: error_message,
82        }
83    }
84}