1use reqwest::Error as ReqError;
2use std::fmt::Formatter;
3use crate::Code;
4
5pub use MiraiError::ServerError;
6pub use MiraiError::HttpError;
7pub use MiraiError::ImpossibleError;
8pub use MiraiError::ClientError;
9
10pub type Result<T> = std::result::Result<T, MiraiError>;
11
12#[derive(Debug)]
13pub enum MiraiError {
14 ServerError(Code, String),
15 ImpossibleError(String),
16 HttpError(ReqError),
17 ClientError(String),
18}
19
20const SUCCESS: Code = 0;
21const WRONG_AUTH_KEY: Code = 1;
22const NO_SUCH_BOT: Code = 2;
23const WRONG_SESSION: Code = 3;
24const UNAUTHORIZED: Code = 4;
25const NO_SUCH_TARGET: Code = 5;
26const NO_SUCH_FILE: Code = 6;
27const PERMISSION_DENIED: Code = 10;
28const MUTED: Code = 20;
29const MESSAGE_TOO_LONG: Code = 30;
30const BAD_REQUEST: Code = 400;
31
32pub(crate) fn assert(code: Code, action: &str) -> Result<()> {
33 let msg = match code {
34 SUCCESS => return Ok(()),
35 WRONG_AUTH_KEY => "Wrong auth key",
36 NO_SUCH_BOT => "No such bot",
37 WRONG_SESSION => "Wrong session",
38 UNAUTHORIZED => "Session wasn't authorized",
39 NO_SUCH_TARGET => "No such target",
40 NO_SUCH_FILE => "No such file",
41 PERMISSION_DENIED => "Bot permission denied",
42 MUTED => "Bot was muted",
43 MESSAGE_TOO_LONG => "Message is too long",
44 BAD_REQUEST => "Bad request",
45
46 _ => "Unknown code"
47 };
48
49 Err(MiraiError::ServerError(code, format!("[{}] {}", action, msg)))
50}
51
52impl std::fmt::Display for MiraiError {
53 fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
54 match self {
55 MiraiError::ServerError(code, s) => f.write_str(&format!("{}: {}", code, s)),
56 MiraiError::ImpossibleError(s) => f.write_str(&format!("{}", s)),
57 MiraiError::HttpError(e) => f.write_str(&e.to_string()),
58 MiraiError::ClientError(e) => f.write_str(e),
59 }
60 }
61}
62
63impl From<ReqError> for MiraiError {
64 fn from(e: ReqError) -> Self {
65 MiraiError::HttpError(e)
66 }
67}