4. Identify the error in this GraphQL input validation snippet:
input ProductInput {
price: Float!
}
resolver addProduct(input: ProductInput) {
if (input.price < 0) {
return 'Price must be positive';
}
saveProduct(input);
return 'Product added';
}
medium
A. Returning a string error instead of throwing an error
B. Missing input type declaration
C. Using Float instead of Int for price
D. No validation for price being zero
Solution
Step 1: Check error handling in resolver
The resolver returns a string on error instead of throwing an error, which may not stop execution properly.
Step 2: Understand proper error signaling
Throwing an error is standard to halt processing and signal failure in GraphQL.
Final Answer:
Returning a string error instead of throwing an error -> Option A
Quick Check:
Errors should be thrown, not returned as strings [OK]
Hint: Throw errors, don't return error strings in resolvers [OK]
Common Mistakes:
Returning error messages instead of throwing
Confusing Float and Int types
Ignoring zero price validation
5. You want to enforce that a user's email input is always lowercase and matches a valid email format in GraphQL. Which combination is the best approach?
hard
A. Use a directive to reject any uppercase letters without transformation
B. Only rely on GraphQL's String type without extra checks
C. Use a custom scalar for email format and transform input to lowercase in resolver
D. Validate email format in the database after saving
Solution
Step 1: Understand validation needs
Email must be valid format and lowercase before saving or processing.
Step 2: Choose best GraphQL validation method
Custom scalar can enforce format; resolver can transform input to lowercase.
Step 3: Evaluate other options
Relying only on String misses validation; directives alone can't transform; database validation is late.
Final Answer:
Use a custom scalar for email format and transform input to lowercase in resolver -> Option C
Quick Check:
Custom scalar + resolver transform = best validation [OK]
Hint: Combine custom scalar and resolver for format and case [OK]