Skip to content

Commit dab0f62

Browse files
authored
Merge pull request http-rs#345 from Fishrock123/Error-from_lossy
feat: add Error::from_display & from_debug
2 parents a906bad + 196244f commit dab0f62

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/error.rs

+23
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,28 @@ impl Error {
161161
pub fn type_name(&self) -> Option<&str> {
162162
self.type_name.as_deref()
163163
}
164+
165+
/// Converts anything which implements `Display` into an `http_types::Error`.
166+
///
167+
/// This is handy for errors which are not `Send + Sync + 'static` because `std::error::Error` requires `Display`.
168+
/// Note that any assiciated context not included in the `Display` output will be lost,
169+
/// and so this may be lossy for some types which implement `std::error::Error`.
170+
///
171+
/// **Note: Prefer `error.into()` via `From<Into<anyhow::Error>>` when possible!**
172+
pub fn from_display<D: Display>(error: D) -> Self {
173+
anyhow::Error::msg(error.to_string()).into()
174+
}
175+
176+
/// Converts anything which implements `Debug` into an `http_types::Error`.
177+
///
178+
/// This is handy for errors which are not `Send + Sync + 'static` because `std::error::Error` requires `Debug`.
179+
/// Note that any assiciated context not included in the `Debug` output will be lost,
180+
/// and so this may be lossy for some types which implement `std::error::Error`.
181+
///
182+
/// **Note: Prefer `error.into()` via `From<Into<anyhow::Error>>` when possible!**
183+
pub fn from_debug<D: Debug>(error: D) -> Self {
184+
anyhow::Error::msg(format!("{:?}", error)).into()
185+
}
164186
}
165187

166188
impl Display for Error {
@@ -180,6 +202,7 @@ impl<E: Into<anyhow::Error>> From<E> for Error {
180202
Self::new(StatusCode::InternalServerError, error)
181203
}
182204
}
205+
183206
impl AsRef<dyn StdError + Send + Sync> for Error {
184207
fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {
185208
self.error.as_ref()

0 commit comments

Comments
 (0)