From 884ea02f5cc2cb93a4919dd4bf0e5373340832da Mon Sep 17 00:00:00 2001 From: Christopher Armstrong Date: Tue, 6 Feb 2018 10:26:50 -0600 Subject: [PATCH] Allow returning failure::Error from handlers (#65) This implements From for Error (by way of `failure::Compat`) and ResponseError for failure::Compat. --- src/error.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/error.rs b/src/error.rs index 4b57d69e..3218f410 100644 --- a/src/error.rs +++ b/src/error.rs @@ -10,6 +10,7 @@ use std::error::Error as StdError; use cookie; use httparse; use futures::Canceled; +use failure; use failure::{Fail, Backtrace}; use http2::Error as Http2Error; use http::{header, StatusCode, Error as HttpError}; @@ -95,6 +96,16 @@ impl From for Error { } } +impl ResponseError for failure::Compat + where T: fmt::Display + fmt::Debug + Sync + Send + 'static +{ } + +impl From for Error { + fn from(err: failure::Error) -> Error { + err.compat().into() + } +} + /// Default error is `InternalServerError` #[cfg(actix_nightly)] default impl ResponseError for T { @@ -651,11 +662,13 @@ pub fn ErrorInternalServerError(err: T) -> InternalError { #[cfg(test)] mod tests { + use std::env; use std::error::Error as StdError; use std::io; use httparse; use http::{StatusCode, Error as HttpError}; use cookie::ParseError as CookieParseError; + use failure; use super::*; #[test] @@ -784,4 +797,18 @@ mod tests { from!(httparse::Error::TooManyHeaders => ParseError::TooLarge); from!(httparse::Error::Version => ParseError::Version); } + + #[test] + fn failure_error() { + const NAME: &str = "RUST_BACKTRACE"; + let old_tb = env::var(NAME); + env::set_var(NAME, "0"); + let error = failure::err_msg("Hello!"); + let resp: Error = error.into(); + assert_eq!(format!("{:?}", resp), "Compat { error: ErrorMessage { msg: \"Hello!\" } }\n\n"); + match old_tb { + Ok(x) => env::set_var(NAME, x), + _ => env::remove_var(NAME), + } + } }