Merge pull request #345 from Fishrock123/Error-from_lossy

feat: add Error::from_display & from_debug
This commit is contained in:
Jeremiah Senkpiel 2021-04-07 11:19:22 -07:00 committed by GitHub
commit dab0f62e6d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 23 additions and 0 deletions

View File

@ -161,6 +161,28 @@ impl Error {
pub fn type_name(&self) -> Option<&str> {
self.type_name.as_deref()
}
/// Converts anything which implements `Display` into an `http_types::Error`.
///
/// This is handy for errors which are not `Send + Sync + 'static` because `std::error::Error` requires `Display`.
/// Note that any assiciated context not included in the `Display` output will be lost,
/// and so this may be lossy for some types which implement `std::error::Error`.
///
/// **Note: Prefer `error.into()` via `From<Into<anyhow::Error>>` when possible!**
pub fn from_display<D: Display>(error: D) -> Self {
anyhow::Error::msg(error.to_string()).into()
}
/// Converts anything which implements `Debug` into an `http_types::Error`.
///
/// This is handy for errors which are not `Send + Sync + 'static` because `std::error::Error` requires `Debug`.
/// Note that any assiciated context not included in the `Debug` output will be lost,
/// and so this may be lossy for some types which implement `std::error::Error`.
///
/// **Note: Prefer `error.into()` via `From<Into<anyhow::Error>>` when possible!**
pub fn from_debug<D: Debug>(error: D) -> Self {
anyhow::Error::msg(format!("{:?}", error)).into()
}
}
impl Display for Error {
@ -180,6 +202,7 @@ impl<E: Into<anyhow::Error>> From<E> for Error {
Self::new(StatusCode::InternalServerError, error)
}
}
impl AsRef<dyn StdError + Send + Sync> for Error {
fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {
self.error.as_ref()