Skip to content

Commit 60c5d73

Browse files
committed
Improve error handling in graphql-query-derive
1 parent dfceebb commit 60c5d73

File tree

9 files changed

+38
-49
lines changed

9 files changed

+38
-49
lines changed

examples/github/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ edition = "2018"
88
anyhow = "1.0"
99
graphql_client = { path = "../../graphql_client" }
1010
serde = "^1.0"
11-
reqwest = { version = "^0.10", features = ["json", "blocking"] }
11+
reqwest = { version = "^0.11", features = ["json", "blocking"] }
1212
prettytable-rs = "^0.7"
1313
structopt = "^0.3"
1414
dotenv = "^0.13"

examples/hasura/Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@ edition = "2018"
66

77
[dev-dependencies]
88
anyhow = "1.0"
9-
graphql_client = { path = "../../graphql_client" }
9+
graphql_client = { path = "../../graphql_client", features = ["reqwest"] }
1010
serde = "1.0"
1111
serde_derive = "1.0"
1212
serde_json = "1.0"
13-
reqwest = { version = "^0.10", features = ["json", "blocking"] }
13+
reqwest = { version = "^0.11", features = ["json", "blocking"] }
1414
prettytable-rs = "0.7.0"
1515
dotenv = "0.13.0"
1616
log = "0.4.3"

graphql-introspection-query/src/introspection_response.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,7 @@ impl IntrospectionResponse {
286286
pub fn as_schema(&self) -> &SchemaContainer {
287287
match self {
288288
IntrospectionResponse::FullResponse(full_response) => &full_response.data,
289-
IntrospectionResponse::Schema(schema) => &schema,
289+
IntrospectionResponse::Schema(schema) => schema,
290290
}
291291
}
292292

graphql_client_codegen/src/codegen.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ fn render_object_literal(
298298
.fields
299299
.iter()
300300
.map(|(name, r#type)| {
301-
let field_name = Ident::new(&name, Span::call_site());
301+
let field_name = Ident::new(name, Span::call_site());
302302
let provided_value = object_map.get(name);
303303
match provided_value {
304304
Some(default_value) => {

graphql_client_codegen/src/codegen/selection.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ fn calculate_selection<'a>(
168168
.iter()
169169
.map(|id| (id, context.query.query.get_selection(*id)))
170170
.filter_map(|(id, selection)| {
171-
VariantSelection::from_selection(&selection, type_id, context.query)
171+
VariantSelection::from_selection(selection, type_id, context.query)
172172
.map(|variant_selection| (*id, selection, variant_selection))
173173
})
174174
.collect();
@@ -188,7 +188,7 @@ fn calculate_selection<'a>(
188188

189189
if let Some((selection_id, selection, _variant)) = variant_selections.get(0) {
190190
let mut variant_struct_name_str =
191-
full_path_prefix(*selection_id, &context.query);
191+
full_path_prefix(*selection_id, context.query);
192192
variant_struct_name_str.reserve(2 + variant_name_str.len());
193193
variant_struct_name_str.push_str("On");
194194
variant_struct_name_str.push_str(variant_name_str);
@@ -258,7 +258,7 @@ fn calculate_selection<'a>(
258258

259259
match selection {
260260
Selection::Field(field) => {
261-
let (graphql_name, rust_name) = context.field_name(&field);
261+
let (graphql_name, rust_name) = context.field_name(field);
262262
let schema_field = field.schema_field(context.schema());
263263
let field_type_id = schema_field.r#type.id;
264264

@@ -295,7 +295,7 @@ fn calculate_selection<'a>(
295295
});
296296
}
297297
TypeId::Object(_) | TypeId::Interface(_) | TypeId::Union(_) => {
298-
let struct_name_string = full_path_prefix(*id, &context.query);
298+
let struct_name_string = full_path_prefix(*id, context.query);
299299

300300
context.push_field(ExpandedField {
301301
struct_id,
@@ -436,7 +436,7 @@ impl<'a> ExpandedVariant<'a> {
436436
fn render(&self) -> TokenStream {
437437
let name_ident = Ident::new(&self.name, Span::call_site());
438438
let optional_type_ident = self.variant_type.as_ref().map(|variant_type| {
439-
let ident = Ident::new(&variant_type, Span::call_site());
439+
let ident = Ident::new(variant_type, Span::call_site());
440440
quote!((#ident))
441441
});
442442

@@ -507,7 +507,7 @@ impl<'a> ExpandedSelection<'a> {
507507

508508
// If the type is aliased, stop here.
509509
if let Some(alias) = self.aliases.iter().find(|alias| alias.struct_id == type_id) {
510-
let fragment_name = Ident::new(&alias.name, Span::call_site());
510+
let fragment_name = Ident::new(alias.name, Span::call_site());
511511
let fragment_name = if alias.boxed {
512512
quote!(Box<#fragment_name>)
513513
} else {

graphql_client_codegen/src/generated_module.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ impl<'a> GeneratedModule<'a> {
3131
fn build_impls(&self) -> Result<TokenStream, BoxError> {
3232
Ok(crate::codegen::response_for_query(
3333
self.root()?,
34-
&self.options,
34+
self.options,
3535
BoundQuery {
3636
query: self.resolved_query,
3737
schema: self.schema,

graphql_client_codegen/src/query.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ fn resolve_fragment(
188188
fragment_definition: &graphql_parser::query::FragmentDefinition,
189189
) -> Result<(), QueryValidationError> {
190190
let graphql_parser::query::TypeCondition::On(on) = &fragment_definition.type_condition;
191-
let on = schema.find_type(&on).ok_or_else(|| {
191+
let on = schema.find_type(on).ok_or_else(|| {
192192
QueryValidationError::new(format!(
193193
"Could not find type `{}` referenced by fragment `{}`",
194194
on, fragment_definition.name

graphql_query_derive/src/attributes.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use crate::{BoxError, GeneralError};
21
use graphql_client_codegen::deprecation::DeprecationStrategy;
32
use graphql_client_codegen::normalization::Normalization;
43

@@ -33,7 +32,10 @@ pub fn extract_attr(ast: &syn::DeriveInput, attr: &str) -> Result<String, syn::E
3332
}
3433
}
3534

36-
Err(syn::Error::new_spanned(ast, "Attribute not found"))
35+
Err(syn::Error::new_spanned(
36+
&ast,
37+
format!("Attribute `{}` not found", attr),
38+
))
3739
}
3840

3941
/// Extract a list of configuration parameter values specified in the `graphql` attribute.
@@ -75,21 +77,21 @@ pub fn extract_attr_list(ast: &syn::DeriveInput, attr: &str) -> Result<Vec<Strin
7577
/// Get the deprecation from a struct attribute in the derive case.
7678
pub fn extract_deprecation_strategy(
7779
ast: &syn::DeriveInput,
78-
) -> Result<DeprecationStrategy, BoxError> {
80+
) -> Result<DeprecationStrategy, syn::Error> {
7981
extract_attr(&ast, "deprecated")?
8082
.to_lowercase()
8183
.as_str()
8284
.parse()
83-
.map_err(|_| GeneralError(DEPRECATION_ERROR.to_owned()).into())
85+
.map_err(|_| syn::Error::new_spanned(ast, DEPRECATION_ERROR.to_owned()))
8486
}
8587

8688
/// Get the deprecation from a struct attribute in the derive case.
87-
pub fn extract_normalization(ast: &syn::DeriveInput) -> Result<Normalization, BoxError> {
89+
pub fn extract_normalization(ast: &syn::DeriveInput) -> Result<Normalization, syn::Error> {
8890
extract_attr(&ast, "normalization")?
8991
.to_lowercase()
9092
.as_str()
9193
.parse()
92-
.map_err(|_| GeneralError(NORMALIZATION_ERROR.to_owned()).into())
94+
.map_err(|_| syn::Error::new_spanned(ast, NORMALIZATION_ERROR))
9395
}
9496

9597
#[cfg(test)]

graphql_query_derive/src/lib.rs

Lines changed: 17 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -8,66 +8,58 @@ use graphql_client_codegen::{
88
};
99
use std::{
1010
env,
11-
fmt::Display,
1211
path::{Path, PathBuf},
1312
};
1413

1514
use proc_macro2::TokenStream;
1615

17-
type BoxError = Box<dyn std::error::Error + 'static>;
18-
19-
#[derive(Debug)]
20-
struct GeneralError(String);
21-
22-
impl Display for GeneralError {
23-
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24-
f.write_str(&self.0)
25-
}
26-
}
27-
28-
impl std::error::Error for GeneralError {}
29-
3016
#[proc_macro_derive(GraphQLQuery, attributes(graphql))]
3117
pub fn derive_graphql_query(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3218
match graphql_query_derive_inner(input) {
3319
Ok(ts) => ts,
34-
Err(err) => panic!("{:?}", err),
20+
Err(err) => err.to_compile_error().into(),
3521
}
3622
}
3723

3824
fn graphql_query_derive_inner(
3925
input: proc_macro::TokenStream,
40-
) -> Result<proc_macro::TokenStream, BoxError> {
26+
) -> Result<proc_macro::TokenStream, syn::Error> {
4127
let input = TokenStream::from(input);
4228
let ast = syn::parse2(input)?;
4329
let (query_path, schema_path) = build_query_and_schema_path(&ast)?;
4430
let options = build_graphql_client_derive_options(&ast, query_path.clone())?;
4531
Ok(
4632
generate_module_token_stream(query_path, &schema_path, options)
4733
.map(Into::into)
48-
.map_err(|err| GeneralError(format!("Code generation failed: {}", err)))?,
34+
.map_err(|err| {
35+
syn::Error::new_spanned(
36+
ast,
37+
format!("Failed to generate GraphQLQuery impl: {}", err),
38+
)
39+
}),
4940
)
5041
}
5142

52-
fn build_query_and_schema_path(input: &syn::DeriveInput) -> Result<(PathBuf, PathBuf), BoxError> {
43+
fn build_query_and_schema_path(input: &syn::DeriveInput) -> Result<(PathBuf, PathBuf), syn::Error> {
5344
let cargo_manifest_dir = env::var("CARGO_MANIFEST_DIR").map_err(|_err| {
54-
GeneralError("Checking that the CARGO_MANIFEST_DIR env variable is defined.".into())
45+
syn::Error::new_spanned(
46+
input,
47+
"Error checking that the CARGO_MANIFEST_DIR env variable is defined.",
48+
)
5549
})?;
5650

57-
let query_path = attributes::extract_attr(input, "query_path")
58-
.map_err(|err| GeneralError(format!("Error extracting query path. {}", err)))?;
51+
let query_path = attributes::extract_attr(input, "query_path")?;
5952
let query_path = format!("{}/{}", cargo_manifest_dir, query_path);
6053
let query_path = Path::new(&query_path).to_path_buf();
61-
let schema_path = attributes::extract_attr(input, "schema_path")
62-
.map_err(|err| GeneralError(format!("Error extracting schema path. {}", err)))?;
54+
let schema_path = attributes::extract_attr(input, "schema_path")?;
6355
let schema_path = Path::new(&cargo_manifest_dir).join(schema_path);
6456
Ok((query_path, schema_path))
6557
}
6658

6759
fn build_graphql_client_derive_options(
6860
input: &syn::DeriveInput,
6961
query_path: PathBuf,
70-
) -> Result<GraphQLClientCodegenOptions, BoxError> {
62+
) -> Result<GraphQLClientCodegenOptions, syn::Error> {
7163
let variables_derives = attributes::extract_attr(input, "variables_derives").ok();
7264
let response_derives = attributes::extract_attr(input, "response_derives").ok();
7365
let custom_scalars_module = attributes::extract_attr(input, "custom_scalars_module").ok();
@@ -96,12 +88,7 @@ fn build_graphql_client_derive_options(
9688

9789
// The user can give a path to a module that provides definitions for the custom scalars.
9890
if let Some(custom_scalars_module) = custom_scalars_module {
99-
let custom_scalars_module = syn::parse_str(&custom_scalars_module).map_err(|err| {
100-
GeneralError(format!(
101-
"Invalid custom scalars module path: {}. {}",
102-
custom_scalars_module, err
103-
))
104-
})?;
91+
let custom_scalars_module = syn::parse_str(&custom_scalars_module)?;
10592

10693
options.set_custom_scalars_module(custom_scalars_module);
10794
}

0 commit comments

Comments
 (0)