http_request_derive/
error.rs

1// SPDX-FileCopyrightText: OpenTalk GmbH <mail@opentalk.eu>
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use bytes::Bytes;
6use http::uri::InvalidUri;
7use snafu::{Location, Snafu};
8use url::Url;
9
10/// Errors that originate from this crate
11#[derive(Debug, Snafu)]
12#[snafu(visibility(pub(crate)))]
13pub enum Error {
14    /// Encountered a `401 UNAUTHORIZED` http status code
15    #[snafu(display("trying to perform an unauthorized request"))]
16    Unauthorized,
17
18    /// Encountered a non-success http status code that was not handled otherwise
19    #[snafu(display("server returned a non-success http status code {status}"))]
20    NonSuccessStatus {
21        /// The returned status code.
22        status: http::StatusCode,
23
24        /// The data returned from the request
25        data: Bytes,
26    },
27
28    /// An error occurred when building a HTTP request
29    #[snafu(display("could not build http request: {source}"))]
30    BuildRequest {
31        /// The source http error
32        source: http::Error,
33    },
34
35    /// Encountered a URL which cannot be a base where a base url was required
36    #[snafu(display("base url {url} cannot be a base"))]
37    UrlCannotBeABase {
38        /// The url which cannot be a base
39        url: Url,
40    },
41
42    /// Couldn't parse a HTTP URI
43    #[snafu(display("couldn't parse uri"))]
44    ParseUri {
45        /// The source invalid uri error
46        source: InvalidUri,
47    },
48
49    /// A query string couldn't be created from the given type
50    #[snafu(display("can't create query string: {message}"))]
51    QueryString {
52        /// A message describing the reason for this error
53        message: String,
54    },
55
56    /// Couldn't create a query from a given string
57    #[cfg(feature = "serde")]
58    #[snafu(display("couldn't build query string from serde url params"))]
59    SerdeUrlParams {
60        /// The source of the serde_url_params error
61        source: serde_url_params::Error,
62    },
63
64    /// serde_json error
65    #[cfg(feature = "serde")]
66    #[snafu(display("serde json error"))]
67    Json {
68        /// The source of the serde_json error
69        source: serde_json::Error,
70    },
71
72    /// custom error returned e.g. by a custom trait implementation in a different crate
73    #[snafu(display("{message}"))]
74    Custom {
75        /// The custom error message
76        message: String,
77
78        /// The location where the error happened
79        location: Location,
80    },
81}
82
83impl Error {
84    /// Create a custom error
85    #[track_caller]
86    pub fn custom(message: String) -> Self {
87        let location = std::panic::Location::caller();
88
89        Error::Custom {
90            message,
91            location: Location::new(location.file(), location.line(), location.column()),
92        }
93    }
94}