1use std::fmt;
4
5use http::StatusCode;
6
7use crate::response::{IntoResponse, Response};
8
9pub type Result<T = Response, E = Error> = std::result::Result<T, E>;
11
12type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
13
14pub struct Error {
23 status: StatusCode,
24 message: String,
25 source: Option<BoxError>,
26}
27
28impl Error {
29 pub fn new(status: StatusCode, message: impl Into<String>) -> Self {
30 Self {
31 status,
32 message: message.into(),
33 source: None,
34 }
35 }
36
37 pub fn with_source(
40 status: StatusCode,
41 message: impl Into<String>,
42 source: impl std::error::Error + Send + Sync + 'static,
43 ) -> Self {
44 Self {
45 status,
46 message: message.into(),
47 source: Some(Box::new(source)),
48 }
49 }
50
51 pub fn downcast_ref<E: std::error::Error + 'static>(&self) -> Option<&E> {
54 self.source.as_deref()?.downcast_ref::<E>()
55 }
56
57 pub fn not_found() -> Self {
58 Self::new(StatusCode::NOT_FOUND, "Not Found")
59 }
60
61 pub fn forbidden() -> Self {
63 Self::new(StatusCode::FORBIDDEN, "Forbidden")
64 }
65
66 pub fn bad_request(message: impl Into<String>) -> Self {
67 Self::new(StatusCode::BAD_REQUEST, message)
68 }
69
70 pub fn unprocessable(message: impl Into<String>) -> Self {
71 Self::new(StatusCode::UNPROCESSABLE_ENTITY, message)
72 }
73
74 pub fn internal(message: impl Into<String>) -> Self {
75 Self::new(StatusCode::INTERNAL_SERVER_ERROR, message)
76 }
77
78 pub fn status(&self) -> StatusCode {
79 self.status
80 }
81
82 pub fn message(&self) -> &str {
83 &self.message
84 }
85
86 pub fn source(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
88 self.source.as_deref()
89 }
90}
91
92impl<E> From<E> for Error
93where
94 E: std::error::Error + Send + Sync + 'static,
95{
96 fn from(err: E) -> Self {
97 Self {
98 status: StatusCode::INTERNAL_SERVER_ERROR,
99 message: err.to_string(),
100 source: Some(Box::new(err)),
101 }
102 }
103}
104
105impl fmt::Debug for Error {
107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 if f.alternate() {
109 return f
110 .debug_struct("Error")
111 .field("status", &self.status)
112 .field("message", &self.message)
113 .field("source", &self.source)
114 .finish();
115 }
116 write!(f, "{}", self.message)?;
117 let mut source = self.source.as_deref().and_then(|err| err.source());
118 if source.is_some() {
119 write!(f, "\n\nCaused by:")?;
120 }
121 while let Some(err) = source {
122 write!(f, "\n {err}")?;
123 source = err.source();
124 }
125 Ok(())
126 }
127}
128
129impl fmt::Display for Error {
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 write!(f, "{}: {}", self.status, self.message)
132 }
133}
134
135#[derive(Debug, Clone)]
138pub struct ErrorReport {
139 pub status: StatusCode,
140 pub message: String,
141 pub causes: Vec<String>,
143}
144
145#[derive(Debug, Clone, Copy)]
150pub(crate) struct Bare;
151
152impl IntoResponse for Error {
153 fn into_response(self) -> Response {
154 if self.status.is_server_error() {
155 let mut causes = Vec::new();
156 let mut source = self.source.as_deref().and_then(|err| err.source());
157 while let Some(err) = source {
158 causes.push(err.to_string());
159 source = err.source();
160 }
161 tracing::event!(
164 target: "glacier",
165 tracing::Level::ERROR,
166 http.response.status_code = i64::from(self.status.as_u16()),
167 error.message = %self.message,
168 error.causes = ?causes,
169 "request failed: {}",
170 self.message
171 );
172 let reason = self.status.canonical_reason().unwrap_or("Error");
173 let mut res = Response::text(reason).with_status(self.status);
174 res.extensions_mut().insert(Bare);
175 res.extensions_mut().insert(ErrorReport {
176 status: self.status,
177 message: self.message,
178 causes,
179 });
180 res
181 } else {
182 let bare = Some(self.message.as_str()) == self.status.canonical_reason();
183 let mut res = Response::text(self.message).with_status(self.status);
184 if bare {
185 res.extensions_mut().insert(Bare);
186 }
187 res
188 }
189 }
190}