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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
use std::fmt::Display;
use std::marker::PhantomData;
use async_graphql::dynamic::TypeRef;
use async_graphql::ErrorExtensionValues;
use async_graphql::Pos;
use async_graphql::ServerError;
use crate::types::GetInputTypeRef;
use crate::Value;
fn get_type_name<T: GetInputTypeRef>() -> String {
let type_ref: TypeRef = <Option<T>>::get_input_type_ref().into();
type_ref.to_string()
}
#[derive(Debug)]
pub struct InputValueError<T> {
message: String,
extensions: Option<ErrorExtensionValues>,
phantom: PhantomData<T>,
}
impl<T> InputValueError<T> {
pub fn new(message: String) -> Self {
Self {
message,
extensions: None,
phantom: PhantomData,
}
}
#[must_use]
pub fn expected_type(actual: Value) -> Self
where
T: GetInputTypeRef,
{
Self::new(format!(
r#"Expected input type "{}", found {}."#,
get_type_name::<T>(),
actual
))
}
#[must_use]
pub fn custom(msg: impl Display) -> Self
where
T: GetInputTypeRef,
{
Self::new(format!(
r#"Failed to parse "{}": {}"#,
get_type_name::<T>(),
msg
))
}
pub fn propagate<U: GetInputTypeRef>(self) -> InputValueError<U>
where
T: GetInputTypeRef,
{
if get_type_name::<T>() != get_type_name::<U>() {
InputValueError::new(format!(
r#"{} (occurred while parsing "{}")"#,
self.message,
get_type_name::<U>()
))
} else {
InputValueError::new(self.message)
}
}
pub fn with_extension(mut self, name: impl AsRef<str>, value: impl Into<Value>) -> Self {
self.extensions
.get_or_insert_with(ErrorExtensionValues::default)
.set(name, value);
self
}
pub fn into_server_error(self, pos: Pos) -> ServerError {
let mut err = ServerError::new(self.message, Some(pos));
err.extensions = self.extensions;
err
}
pub fn into_arg_error(self, name: &str) -> crate::Error {
let mut error = crate::Error::new(format!(
"Invalid value for argument \"{}\": {}",
name, self.message
));
error.extensions = self.extensions;
error
}
pub fn into_field_error(self, name: &str) -> crate::Error {
let mut error = crate::Error::new(format!(
"Invalid value for field \"{}\": {}",
name, self.message
));
error.extensions = self.extensions;
error
}
}
impl<T: GetInputTypeRef> From<async_graphql::Error> for InputValueError<T> {
fn from(value: async_graphql::Error) -> Self {
let mut err = Self::custom(value.message);
err.extensions = value.extensions;
err
}
}
impl<T> From<InputValueError<T>> for async_graphql::Error {
fn from(value: InputValueError<T>) -> Self {
Self {
message: value.message,
source: None,
extensions: value.extensions,
}
}
}
pub type InputValueResult<T> = Result<T, InputValueError<T>>;