From 2e9408e5f6dc6382f8e8233fc7d87125da879e28 Mon Sep 17 00:00:00 2001 From: Paul Colomiets <paul@colomiets.name> Date: Tue, 10 Jul 2018 18:07:18 +0300 Subject: [PATCH] Consistent error serializing for GraphQLError (#207) GraphQL spec requires every error contain `{"message": "field"}`. Every error in juniper except ones fixed here are reported consistently with this style. This commit fixes ones left. --- juniper/src/integrations/serde.rs | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/juniper/src/integrations/serde.rs b/juniper/src/integrations/serde.rs index 72048c79..e4eb46c8 100644 --- a/juniper/src/integrations/serde.rs +++ b/juniper/src/integrations/serde.rs @@ -10,6 +10,11 @@ use parser::{ParseError, SourcePosition, Spanning}; use validation::RuleError; use {GraphQLError, Value}; +#[derive(Serialize)] +struct SerializeHelper { + message: &'static str, +} + impl ser::Serialize for ExecutionError { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where @@ -45,11 +50,21 @@ impl<'a> ser::Serialize for GraphQLError<'a> { GraphQLError::ParseError(ref err) => vec![err].serialize(serializer), GraphQLError::ValidationError(ref errs) => errs.serialize(serializer), GraphQLError::NoOperationProvided => { - serializer.serialize_str("Must provide an operation") + [ + SerializeHelper { message: "Must provide an operation" } + ].serialize(serializer) + } + GraphQLError::MultipleOperationsProvided => { + [SerializeHelper { + message: "Must provide operation name \ + if query contains multiple operations", + }].serialize(serializer) + } + GraphQLError::UnknownOperationName => { + [ + SerializeHelper { message: "Unknown operation" } + ].serialize(serializer) } - GraphQLError::MultipleOperationsProvided => serializer - .serialize_str("Must provide operation name if query contains multiple operations"), - GraphQLError::UnknownOperationName => serializer.serialize_str("Unknown operation"), } } } @@ -261,7 +276,9 @@ impl ser::Serialize for Value { #[cfg(test)] mod tests { use serde_json::from_str; + use serde_json::to_string; use ast::InputValue; + use super::GraphQLError; #[test] fn int() { @@ -277,4 +294,10 @@ mod tests { assert_eq!(from_str::<InputValue>("123567890123").unwrap(), InputValue::float(123567890123.0)); } + + #[test] + fn errors() { + assert_eq!(to_string(&GraphQLError::UnknownOperationName).unwrap(), + r#"[{"message":"Unknown operation"}]"#); + } }