gitea_sdk/
error.rs

1use core::fmt;
2use std::{error::Error, fmt::Display};
3
4use reqwest::StatusCode;
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum TeatimeErrorKind {
8    HttpError,
9    SerializationError,
10    Other,
11}
12
13impl Display for TeatimeErrorKind {
14    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
15        match self {
16            TeatimeErrorKind::HttpError => write!(f, "HTTP error"),
17            TeatimeErrorKind::SerializationError => write!(f, "Serialization error"),
18            TeatimeErrorKind::Other => write!(f, "error"),
19        }
20    }
21}
22
23/// Represents some kind of error that can occur when interacting with the Gitea API.
24/// This simply wraps a message and a status code.
25#[derive(Debug, Clone)]
26pub struct TeatimeError {
27    pub message: String,
28    pub kind: TeatimeErrorKind,
29    pub status_code: reqwest::StatusCode,
30}
31impl Error for TeatimeError {}
32impl Display for TeatimeError {
33    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34        write!(f, "{}", self.message)
35    }
36}
37
38/// A type alias for a [std::result::Result] that uses [TeatimeError] as the error type.
39/// We define this purely for convenience.
40pub type Result<T> = std::result::Result<T, TeatimeError>;
41
42/// Converts a [reqwest::Error] into a [TeatimeError].
43/// This method exists for us to be able to directly call the unwrap operator (`?`) on the result
44/// of a [reqwest::Result].
45impl From<reqwest::Error> for TeatimeError {
46    fn from(err: reqwest::Error) -> Self {
47        let mut kind = TeatimeErrorKind::HttpError;
48        if err.is_decode() {
49            kind = TeatimeErrorKind::SerializationError;
50        }
51        TeatimeError {
52            message: format!("{}", err),
53            status_code: err.status().unwrap_or(StatusCode::BAD_REQUEST),
54            kind,
55        }
56    }
57}
58
59impl From<Box<dyn Error>> for TeatimeError {
60    fn from(err: Box<dyn Error>) -> Self {
61        TeatimeError {
62            message: format!("{}", err),
63            status_code: StatusCode::BAD_REQUEST,
64            kind: TeatimeErrorKind::Other,
65        }
66    }
67}