rrw/error.rs
1use std::fmt::{Debug, Display};
2
3use serde::Deserialize;
4
5/// The errors that may occure when accessing a REST-API.
6///
7/// To determine the type of error, the following things are done in order:
8///
9/// - Send a HTTP(S)-Request. If failed, return [Error::Request].
10/// - Try to parse it into the wanted return type. If failed:
11/// - Try to parse it into the error type `T`. If successfull, return [Error::Api]
12/// - Otherwise return a [Error::BodyNotParsable] with the error from trying to convert into the
13/// wanted return type.
14///
15/// One common type for `T` is [StandardRestError], but `T` can be custom as log as
16/// `T: Display + Debug` is satisfied.
17#[derive(Debug)]
18pub enum Error<T> {
19 /// Failed to send the request or parse the bytes of the response.
20 Request(reqwest::Error),
21 /// The API returned a error.
22 Api(T),
23 /// The API returned something unreadable.
24 BodyNotParsable(serde_json::Error),
25}
26
27impl<T: Display> Display for Error<T> {
28 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29 match self {
30 Error::Request(e) => write!(f, "Failed to request: {}", e),
31 Error::Api(e) => write!(f, "Api gave an error: {}", e),
32 Error::BodyNotParsable(e) => write!(f, "The response body could not be parsed {}", e),
33 }
34 }
35}
36
37impl<T: Display + Debug> std::error::Error for Error<T> {}
38
39/// A standard error scheme found in many REST-API responses.
40///
41/// This consists of a status code, a error indicator and a message.
42///
43/// A example of a [StandardRestError] in JSON would be:
44///
45/// ```json
46/// {
47/// "statusCode": 400,
48/// "error": true,
49/// "msg": "Missing query parameter."
50/// }
51/// ```
52///
53/// Should be used in combination with [Error].
54///
55#[derive(Deserialize, Debug)]
56#[serde(rename_all = "camelCase")]
57pub struct StandardRestError {
58 /// The error code return from the API.
59 pub status_code: usize,
60 /// A indicator that a error occured.
61 pub error: bool,
62 /// A error message.
63 pub msg: String,
64}
65
66impl Display for StandardRestError {
67 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68 write!(f, "{}", self.msg)
69 }
70}