spectacles_rest/
errors.rs

1use std::{
2    error::Error as StdError,
3    fmt::{Display, Formatter, Result as FmtResult},
4    io::Error as IoError,
5    num::ParseIntError,
6    result::Result as StdResult,
7};
8
9use reqwest::Error as ReqwestError;
10use reqwest::StatusCode;
11use serde_json::Error as JsonError;
12use tokio::timer::Error as TimerError;
13
14/// A modified result type which encompasses the global error type.
15pub type Result<T> = StdResult<T, Error>;
16
17/// An HTTP error encountered as a result of a request sent to the Discord API.
18#[derive(Debug)]
19pub struct APIError {
20    /// The error message returned my Discord.
21    pub message: String,
22    /// The error code returned by Discord.
23    pub code: i32,
24    /// The HTTP status code of the request.
25    pub http_status: StatusCode,
26}
27
28impl StdError for APIError {
29    fn description(&self) -> &str {
30        self.message.as_str()
31    }
32}
33
34impl Display for APIError {
35    fn fmt(&self, f: &mut Formatter) -> FmtResult {
36        f.write_str(self.description())
37    }
38}
39/// Represents a global error which can occur throughout the library.
40#[derive(Debug)]
41pub enum Error {
42    Json(JsonError),
43    Discord(APIError),
44    ParseInt(ParseIntError),
45    Timer(TimerError),
46    Reqwest(ReqwestError),
47    InvalidTokenError,
48    Io(IoError),
49}
50
51impl Display for Error {
52    fn fmt(&self, f: &mut Formatter) -> FmtResult {
53        f.write_str(self.description())
54    }
55}
56
57impl StdError for Error {
58    fn description(&self) -> &str {
59        match self {
60            Error::Discord(e) => e.description(),
61            Error::Reqwest(e) => e.description(),
62            Error::ParseInt(e) => e.description(),
63            Error::Timer(e) => e.description(),
64            Error::Io(e) => e.description(),
65            Error::Json(e) => e.description(),
66            Error::InvalidTokenError =>
67                "The token provided was not accepted by Discord. Please check that your token is correct and try again."
68        }
69    }
70}
71
72impl From<IoError> for Error {
73    fn from(err: IoError) -> Self {
74        Error::Io(err)
75    }
76}
77
78impl From<ReqwestError> for Error {
79    fn from(err: ReqwestError) -> Self {
80        if let Some(t) = err.status() {
81            match t.as_u16() {
82                401 => Error::InvalidTokenError,
83                _ => Error::Reqwest(err)
84            }
85        } else {
86            Error::Reqwest(err)
87        }
88    }
89}
90
91impl From<JsonError> for Error {
92    fn from(err: JsonError) -> Self {
93        Error::Json(err)
94    }
95}
96
97impl From<TimerError> for Error {
98    fn from(err: TimerError) -> Self {
99        Error::Timer(err)
100    }
101}
102
103impl From<ParseIntError> for Error {
104    fn from(err: ParseIntError) -> Self {
105        Error::ParseInt(err)
106    }
107}