Skip to content

Commit 2e9408e

Browse files
tailhookLegNeato
authored andcommitted
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.
1 parent 569bc16 commit 2e9408e

File tree

1 file changed

+27
-4
lines changed

1 file changed

+27
-4
lines changed

juniper/src/integrations/serde.rs

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,11 @@ use parser::{ParseError, SourcePosition, Spanning};
1010
use validation::RuleError;
1111
use {GraphQLError, Value};
1212

13+
#[derive(Serialize)]
14+
struct SerializeHelper {
15+
message: &'static str,
16+
}
17+
1318
impl ser::Serialize for ExecutionError {
1419
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1520
where
@@ -45,11 +50,21 @@ impl<'a> ser::Serialize for GraphQLError<'a> {
4550
GraphQLError::ParseError(ref err) => vec![err].serialize(serializer),
4651
GraphQLError::ValidationError(ref errs) => errs.serialize(serializer),
4752
GraphQLError::NoOperationProvided => {
48-
serializer.serialize_str("Must provide an operation")
53+
[
54+
SerializeHelper { message: "Must provide an operation" }
55+
].serialize(serializer)
56+
}
57+
GraphQLError::MultipleOperationsProvided => {
58+
[SerializeHelper {
59+
message: "Must provide operation name \
60+
if query contains multiple operations",
61+
}].serialize(serializer)
62+
}
63+
GraphQLError::UnknownOperationName => {
64+
[
65+
SerializeHelper { message: "Unknown operation" }
66+
].serialize(serializer)
4967
}
50-
GraphQLError::MultipleOperationsProvided => serializer
51-
.serialize_str("Must provide operation name if query contains multiple operations"),
52-
GraphQLError::UnknownOperationName => serializer.serialize_str("Unknown operation"),
5368
}
5469
}
5570
}
@@ -261,7 +276,9 @@ impl ser::Serialize for Value {
261276
#[cfg(test)]
262277
mod tests {
263278
use serde_json::from_str;
279+
use serde_json::to_string;
264280
use ast::InputValue;
281+
use super::GraphQLError;
265282

266283
#[test]
267284
fn int() {
@@ -277,4 +294,10 @@ mod tests {
277294
assert_eq!(from_str::<InputValue>("123567890123").unwrap(),
278295
InputValue::float(123567890123.0));
279296
}
297+
298+
#[test]
299+
fn errors() {
300+
assert_eq!(to_string(&GraphQLError::UnknownOperationName).unwrap(),
301+
r#"[{"message":"Unknown operation"}]"#);
302+
}
280303
}

0 commit comments

Comments
 (0)