Skip to main content

twikit/
error.rs

1//! Error types.
2
3use reqwest::header::HeaderMap;
4use serde_json::Value;
5use thiserror::Error as ThisError;
6
7/// Crate result alias.
8pub type Result<T> = std::result::Result<T, Error>;
9
10/// Errors returned by the client.
11#[derive(Debug, ThisError)]
12pub enum Error {
13    /// Request failed before a response was received.
14    #[error("request failed: {0}")]
15    Request(#[from] reqwest::Error),
16    /// JSON serialization or parsing failed.
17    #[error("json error: {0}")]
18    Json(#[from] serde_json::Error),
19    /// URL parsing failed.
20    #[error("url error: {0}")]
21    Url(#[from] url::ParseError),
22    /// I/O failed.
23    #[error("io error: {0}")]
24    Io(#[from] std::io::Error),
25    /// Cookie store failed.
26    #[error("cookie error: {0}")]
27    Cookie(String),
28    /// HTTP response mapped to a Twitter/X API error.
29    #[error("{kind}: status {status}, body: {body}")]
30    Api {
31        /// Error kind.
32        kind: ApiErrorKind,
33        /// HTTP status code.
34        status: u16,
35        /// Response headers.
36        headers: Box<HeaderMap>,
37        /// Response body.
38        body: String,
39        /// Parsed JSON body when available.
40        json: Option<Value>,
41    },
42    /// Expected data was not present in the response.
43    #[error("missing field or object: {0}")]
44    Missing(&'static str),
45    /// API payload was structurally valid JSON but unsupported.
46    #[error("unsupported payload: {0}")]
47    Unsupported(String),
48    /// Flow reached a task that needs caller input or a configured integration.
49    #[error("interactive flow required: {0}")]
50    Interactive(String),
51}
52
53/// HTTP/API error class.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum ApiErrorKind {
56    /// 400.
57    BadRequest,
58    /// 401.
59    Unauthorized,
60    /// 403.
61    Forbidden,
62    /// 404.
63    NotFound,
64    /// 408.
65    RequestTimeout,
66    /// 429.
67    TooManyRequests,
68    /// 5xx.
69    ServerError,
70    /// Account suspended from error code 37 or 64.
71    AccountSuspended,
72    /// Account locked from error code 326.
73    AccountLocked,
74    /// Duplicate tweet from error code 187.
75    DuplicateTweet,
76    /// Invalid media from error code 324.
77    InvalidMedia,
78    /// Tweet is unavailable.
79    TweetNotAvailable,
80    /// User not found.
81    UserNotFound,
82    /// User unavailable.
83    UserUnavailable,
84    /// Any other API error.
85    Twitter,
86}
87
88impl std::fmt::Display for ApiErrorKind {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        let s = match self {
91            Self::BadRequest => "bad request",
92            Self::Unauthorized => "unauthorized",
93            Self::Forbidden => "forbidden",
94            Self::NotFound => "not found",
95            Self::RequestTimeout => "request timeout",
96            Self::TooManyRequests => "too many requests",
97            Self::ServerError => "server error",
98            Self::AccountSuspended => "account suspended",
99            Self::AccountLocked => "account locked",
100            Self::DuplicateTweet => "duplicate tweet",
101            Self::InvalidMedia => "invalid media",
102            Self::TweetNotAvailable => "tweet not available",
103            Self::UserNotFound => "user not found",
104            Self::UserUnavailable => "user unavailable",
105            Self::Twitter => "twitter error",
106        };
107        f.write_str(s)
108    }
109}
110
111pub(crate) fn kind_for_status(status: u16) -> ApiErrorKind {
112    match status {
113        400 => ApiErrorKind::BadRequest,
114        401 => ApiErrorKind::Unauthorized,
115        403 => ApiErrorKind::Forbidden,
116        404 => ApiErrorKind::NotFound,
117        408 => ApiErrorKind::RequestTimeout,
118        429 => ApiErrorKind::TooManyRequests,
119        500..=599 => ApiErrorKind::ServerError,
120        _ => ApiErrorKind::Twitter,
121    }
122}