1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use reqwest::Error;
use serde::Deserialize;
use std::collections::HashMap;
use std::fmt;
use std::fmt::Formatter;
pub struct GraphQLError {
message: String,
json: Option<Vec<GraphQLErrorMessage>>,
}
#[derive(Deserialize, Debug)]
pub struct GraphQLErrorMessage {
message: String,
locations: Option<Vec<GraphQLErrorLocation>>,
extensions: Option<HashMap<String, String>>,
path: Option<Vec<GraphQLErrorPathParam>>,
}
#[derive(Deserialize, Debug)]
pub struct GraphQLErrorLocation {
line: u32,
column: u32,
}
#[derive(Deserialize, Debug)]
#[serde(untagged)]
pub enum GraphQLErrorPathParam {
String(String),
Number(u32),
}
impl GraphQLError {
pub fn from_str(message: &str) -> Self {
Self {
message: String::from(message),
json: None,
}
}
pub fn from_json(json: Vec<GraphQLErrorMessage>) -> Self {
Self {
message: String::from("Look at json field for more details"),
json: Some(json),
}
}
pub fn message(&self) -> &str {
&self.message
}
pub fn json(&self) -> &Option<Vec<GraphQLErrorMessage>> {
&self.json
}
}
fn format(err: &GraphQLError, f: &mut Formatter<'_>) -> fmt::Result {
writeln!(f, "\nGQLClient Error: {}", err.message)?;
if err.json.is_none() {
return Ok(());
}
let errors = err.json.as_ref();
for err in errors.unwrap() {
writeln!(f, "Message: {}", err.message)?;
}
Ok(())
}
impl fmt::Display for GraphQLError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
format(self, f)
}
}
impl fmt::Debug for GraphQLError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
format(&self, f)
}
}
impl std::convert::From<reqwest::Error> for GraphQLError {
fn from(error: Error) -> Self {
Self {
message: error.to_string(),
json: None,
}
}
}