diff --git a/src/error.rs b/src/error.rs index f6609eaf..6c79bf40 100644 --- a/src/error.rs +++ b/src/error.rs @@ -86,7 +86,7 @@ impl ServerError { /// use async_graphql::{Failure, Error, ServerError, Pos}; /// /// let bytes = vec![0, 159]; - /// let err: Error = String::from_utf8(bytes).map_err(Failure).unwrap_err().into(); + /// let err: Error = String::from_utf8(bytes).map_err(Failure::new).unwrap_err().into(); /// let server_err: ServerError = err.into_server_error(Pos { line: 1, column: 1 }); /// assert!(server_err.concrete_error::().is_some()); /// ``` @@ -265,11 +265,11 @@ impl From for Error { } } -impl From> for Error { - fn from(e: Failure) -> Self { +impl From for Error { + fn from(e: Failure) -> Self { Self { - message: e.0.to_string(), - error: Some(Arc::new(e.0)), + message: e.message, + error: Some(e.error), extensions: None, } } @@ -388,7 +388,8 @@ impl ErrorExtensions for &E { } } -impl ErrorExtensions for Failure { +impl ErrorExtensions for Failure { + #[inline] fn extend(self) -> Error { Error::from(self) } @@ -431,18 +432,24 @@ where /// A wrapper around a dynamic error type. #[derive(Debug)] -pub struct Failure(pub T); +pub struct Failure { + message: String, + error: Arc, +} -impl From for Failure { +impl From for Failure { fn from(err: T) -> Self { - Self(err) + Self { + message: err.to_string(), + error: Arc::new(err), + } } } -impl Failure { +impl Failure { /// Create a new failure. #[inline] - pub fn new(err: T) -> Self { - Self(err) + pub fn new(err: T) -> Self { + From::from(err) } } diff --git a/tests/error_ext.rs b/tests/error_ext.rs index 10ad7df7..b723f823 100644 --- a/tests/error_ext.rs +++ b/tests/error_ext.rs @@ -92,23 +92,23 @@ pub async fn test_failure() { #[Object] impl Query { async fn failure(&self) -> Result { - Err(Failure(MyError::Error1).into()) + Err(Failure::new(MyError::Error1).into()) } async fn failure2(&self) -> Result { - Err(Failure(MyError::Error2))?; + Err(Failure::new(MyError::Error2))?; Ok(1) } async fn failure3(&self) -> Result { - Err(Failure(MyError::Error1) + Err(Failure::new(MyError::Error1) .extend_with(|_, values| values.set("a", 1)) .extend_with(|_, values| values.set("b", 2)))?; Ok(1) } async fn failure4(&self) -> Result { - Err(Failure(MyError::Error2)) + Err(Failure::new(MyError::Error2)) .extend_err(|_, values| values.set("a", 1)) .extend_err(|_, values| values.set("b", 2))?; Ok(1) @@ -166,3 +166,21 @@ pub async fn test_failure() { }) ); } + +#[tokio::test] +pub async fn test_failure2() { + #[derive(thiserror::Error, Debug, PartialEq)] + enum MyError { + #[error("error1")] + Error1, + } + + struct Query; + + #[Object] + impl Query { + async fn failure(&self) -> Result { + Err(MyError::Error1)? + } + } +}