1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use std::fmt;

use serde::ser;

use crate::RequestError;

#[derive(Debug, derive_more::From)]
pub(crate) enum Error {
    Custom(String),
    TopLevelNotStruct,
    Fmt(std::fmt::Error),
    Io(std::io::Error),
    Json(serde_json::Error),
}

impl ser::Error for Error {
    fn custom<T>(msg: T) -> Self
    where
        T: fmt::Display,
    {
        Self::Custom(msg.to_string())
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Custom(s) => write!(f, "Custom serde error: {s}"),
            Self::TopLevelNotStruct => write!(f, "Multipart supports only structs at top level"),
            Self::Fmt(inner) => write!(f, "Formatting error: {inner}"),
            Self::Io(inner) => write!(f, "Io error: {inner}"),
            Self::Json(inner) => write!(f, "Json (de)serialization error: {inner}"),
        }
    }
}

impl std::error::Error for Error {}

impl From<Error> for RequestError {
    fn from(err: Error) -> Self {
        match err {
            Error::Io(ioerr) => RequestError::Io(ioerr),

            // This should be ok since we (hopefuly) don't write request those may trigger errors
            // and `Error` is internal.
            e => unreachable!(
                "we don't create requests those fail to serialize (if you see this, open an issue \
                 :|): {}",
                e
            ),
        }
    }
}