Skip to main content

anticaptcha/
error.rs

1//! Everything that can go wrong while solving a captcha.
2
3/// Errors returned by this library.
4#[derive(Debug, thiserror::Error)]
5#[non_exhaustive]
6pub enum Error {
7    /// A task is missing a required parameter, or a value is out of range.
8    /// Nothing was sent to the API.
9    #[error("{0}")]
10    InvalidTask(String),
11
12    /// The API could not be reached.
13    #[error("network error: {0}")]
14    Network(#[from] reqwest::Error),
15
16    /// The API answered with something that is not the JSON we expect.
17    #[error("could not parse the API response: {message}; raw response: {raw}")]
18    BadResponse {
19        message: String,
20        /// First 500 characters of what the API actually sent.
21        raw: String,
22    },
23
24    /// The API answered with a non-zero `errorId`.
25    /// See <https://anti-captcha.com/apidoc/errors> for the list of codes.
26    #[error("API error {error_id} {error_code}: {description}")]
27    Api {
28        error_id: i64,
29        error_code: String,
30        description: String,
31    },
32
33    /// The task was still unsolved when the waiting limit ran out.
34    #[error("the task was not solved in {0} seconds")]
35    Timeout(u64),
36
37    /// A captcha image file could not be read.
38    #[error("could not read {path}: {source}")]
39    Io {
40        path: String,
41        #[source]
42        source: std::io::Error,
43    },
44}
45
46impl Error {
47    /// The API error code, e.g. `ERROR_ZERO_BALANCE`, when this is an [`Error::Api`].
48    pub fn api_error_code(&self) -> Option<&str> {
49        match self {
50            Error::Api { error_code, .. } => Some(error_code),
51            _ => None,
52        }
53    }
54
55    /// True when retrying the very same task could still succeed.
56    pub fn is_retryable(&self) -> bool {
57        match self {
58            Error::Network(_) | Error::Timeout(_) => true,
59            Error::Api { error_code, .. } => matches!(
60                error_code.as_str(),
61                "ERROR_NO_SLOT_AVAILABLE"
62                    | "ERROR_SERVICE_OVERLOAD"
63                    | "ERROR_RATE_LIMIT"
64                    | "ERROR_CAPTCHA_UNSOLVABLE"
65            ),
66            _ => false,
67        }
68    }
69}
70
71/// Shorthand for a result carrying our [`Error`].
72pub type Result<T> = std::result::Result<T, Error>;