Skip to main content

onebot_api/
error.rs

1// use std::fmt::{Display, Formatter};
2use thiserror::Error as TError;
3
4pub type APIResult<T> = Result<T, APIRequestError>;
5
6#[derive(Debug, TError, Clone)]
7pub enum APIRequestError {
8	#[error("There is no result returned in time")]
9	Timeout,
10	#[error("The request failed with code: {:?}", code)]
11	HttpError { code: HttpCode },
12}
13
14#[derive(Debug, Clone)]
15pub enum HttpCode {
16	Ok,
17	BadRequest,
18	Unauthorized,
19	Forbidden,
20	NotFound,
21	NotAcceptable,
22	Unknown(i32),
23}
24
25impl HttpCode {
26	pub fn from_http_code(http_code: i32) -> Self {
27		match http_code {
28			200 => Self::Ok,
29			400 => Self::BadRequest,
30			401 => Self::Unauthorized,
31			403 => Self::Forbidden,
32			404 => Self::NotFound,
33			406 => Self::NotAcceptable,
34			other => Self::Unknown(other),
35		}
36	}
37
38	pub fn retcode_to_http_code(retcode: i32) -> i32 {
39		retcode - 1000
40	}
41
42	pub fn from_retcode(retcode: i32) -> Self {
43		Self::from_http_code(Self::retcode_to_http_code(retcode))
44	}
45}
46
47impl From<i32> for HttpCode {
48	fn from(value: i32) -> Self {
49		Self::from_http_code(value)
50	}
51}