http_request_derive/
error.rs1use bytes::Bytes;
6use http::{StatusCode, uri::InvalidUri};
7use snafu::{Location, Snafu};
8use url::Url;
9
10#[derive(Debug, Snafu)]
12#[snafu(visibility(pub(crate)))]
13pub enum Error {
14 #[snafu(display("server returned a non-success http status code {status}"))]
16 NonSuccessStatus {
17 status: StatusCode,
19
20 body: Bytes,
22 },
23
24 #[snafu(display("could not build http request: {source}"))]
26 BuildRequest {
27 source: http::Error,
29 },
30
31 #[snafu(display("base url {url} cannot be a base"))]
33 UrlCannotBeABase {
34 url: Url,
36 },
37
38 #[snafu(display("couldn't parse uri"))]
40 ParseUri {
41 source: InvalidUri,
43 },
44
45 #[snafu(display("can't create query string: {message}"))]
47 QueryString {
48 message: String,
50 },
51
52 #[cfg(feature = "serde")]
54 #[snafu(display("couldn't build query string from serde url params"))]
55 SerdeUrlParams {
56 source: serde_url_params::Error,
58 },
59
60 #[cfg(feature = "serde")]
62 #[snafu(display("serde json error"))]
63 Json {
64 source: serde_json::Error,
66 },
67
68 #[snafu(display("{message}"))]
70 Custom {
71 message: String,
73
74 location: Location,
76 },
77}
78
79impl Error {
80 #[track_caller]
82 pub fn custom(message: String) -> Self {
83 let location = std::panic::Location::caller();
84
85 Error::Custom {
86 message,
87 location: Location::new(location.file(), location.line(), location.column()),
88 }
89 }
90
91 pub const fn is_unauthorized(&self) -> bool {
93 self.is_specific_http_error_status(&StatusCode::UNAUTHORIZED)
94 }
95
96 pub const fn is_not_found(&self) -> bool {
98 self.is_specific_http_error_status(&StatusCode::NOT_FOUND)
99 }
100
101 pub const fn is_bad_request(&self) -> bool {
103 self.is_specific_http_error_status(&StatusCode::BAD_REQUEST)
104 }
105
106 pub const fn is_internal_server_error(&self) -> bool {
108 self.is_specific_http_error_status(&StatusCode::INTERNAL_SERVER_ERROR)
109 }
110
111 pub const fn is_http_error_status(&self) -> bool {
113 matches!(self, Self::NonSuccessStatus { .. })
114 }
115
116 pub const fn is_specific_http_error_status(&self, specific_status: &StatusCode) -> bool {
118 matches!(self, Self::NonSuccessStatus { status,.. } if status.as_u16() == specific_status.as_u16())
119 }
120}