1use reqwest::header::HeaderMap;
4use serde_json::Value;
5use thiserror::Error as ThisError;
6
7pub type Result<T> = std::result::Result<T, Error>;
9
10#[derive(Debug, ThisError)]
12pub enum Error {
13 #[error("request failed: {0}")]
15 Request(#[from] reqwest::Error),
16 #[error("json error: {0}")]
18 Json(#[from] serde_json::Error),
19 #[error("url error: {0}")]
21 Url(#[from] url::ParseError),
22 #[error("io error: {0}")]
24 Io(#[from] std::io::Error),
25 #[error("cookie error: {0}")]
27 Cookie(String),
28 #[error("{kind}: status {status}, body: {body}")]
30 Api {
31 kind: ApiErrorKind,
33 status: u16,
35 headers: Box<HeaderMap>,
37 body: String,
39 json: Option<Value>,
41 },
42 #[error("missing field or object: {0}")]
44 Missing(&'static str),
45 #[error("unsupported payload: {0}")]
47 Unsupported(String),
48 #[error("interactive flow required: {0}")]
50 Interactive(String),
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum ApiErrorKind {
56 BadRequest,
58 Unauthorized,
60 Forbidden,
62 NotFound,
64 RequestTimeout,
66 TooManyRequests,
68 ServerError,
70 AccountSuspended,
72 AccountLocked,
74 DuplicateTweet,
76 InvalidMedia,
78 TweetNotAvailable,
80 UserNotFound,
82 UserUnavailable,
84 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}