การจัดการข้อผิดพลาดแบบกำหนดเองใน GraphQL
นำการจัดการข้อยกเว้นแบบกำหนดเองมาใช้ และจัดรูปแบบการตอบกลับข้อผิดพลาดตามแนวทางปฏิบัติที่ดีของ GraphQL
การจัดการข้อผิดพลาดแบบกำหนดเองใน GraphQL เป็นบทเรียน GraphQL APIs with Spring Boot ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน GraphQL APIs with Spring Boot และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส GraphQL APIs with Spring Boot มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Understanding GraphQL Errors
When something goes wrong in a GraphQL operation, the server typically returns an errors array in the response. This array contains objects describing what went wrong.
By default, these error messages can be generic or even expose sensitive internal details like stack traces, which isn't ideal for production APIs.
Spring GraphQL's Default Behavior
Out-of-the-box, Spring GraphQL often maps Java exceptions (like RuntimeException) thrown by your data fetchers into a standard DataFetchingException. While functional, this default behavior might not provide the specific, user-friendly details your clients need.
Why Customize Error Responses?
Customizing error handling offers significant benefits:
- Improved UX: Provide clear, actionable messages for end-users.
- Enhanced Security: Prevent exposure of sensitive internal information (e.g., database errors, full stack traces).
- Client-Side Logic: Include custom error codes or details that frontend applications can use to react specifically to different error types.
Meet DataFetcherExceptionResolver
In Spring GraphQL, the primary way to customize error responses is by implementing the DataFetcherExceptionResolver interface. This powerful interface allows you to intercept any exception thrown by a data fetcher and transform it into a structured GraphQLError object.
Define Your Custom Error
First, let's create a simple custom exception. This helps categorize specific error scenarios in your application. For example, a ResourceNotFoundException:
public class ResourceNotFoundException extends RuntimeException {
private final String resourceId;
public ResourceNotFoundException(String message, String resourceId) {
super(message);
this.resourceId = resourceId;
}
public String getResourceId() {
return resourceId;
}
}Building Your Custom Resolver
Now, we'll create a class that implements DataFetcherExceptionResolver. This class will inspect the thrown exception and build a custom GraphQLError, potentially adding specific details via extensions.
import graphql.GraphQLError;
import graphql.execution.DataFetcherExceptionHandler;
import graphql.execution.DataFetcherExceptionHandlerParameters;
import graphql.execution.DataFetcherExceptionHandlerResult;
import graphql.error.ErrorType;
import java.util.HashMap;
import java.util.Map;
public class CustomExceptionResolver implements DataFetcherExceptionHandler {
@Override
public DataFetcherExceptionHandlerResult onException(
DataFetcherExceptionHandlerParameters handlerParameters) {
Throwable exception = handlerParameters.getException();
if (exception instanceof ResourceNotFoundException) {
ResourceNotFoundException rnfEx = (ResourceNotFoundException) exception;
Map<String, Object> extensions = new HashMap<>();
extensions.put("errorCode", "NOT_FOUND");
extensions.put("resourceId", rnfEx.getResourceId());
GraphQLError error = GraphQLError.newError()
.message(rnfEx.getMessage())
.locations(handlerParameters.getSourceLocation())
.path(handlerParameters.getPath())
.extensions(extensions)
.errorType(ErrorType.DataFetchingException)
.build();
return DataFetcherExceptionHandlerResult.newResult().error(error).build();
}
// Fallback for unhandled exceptions
return DataFetcherExceptionHandlerResult.newResult()
.error(GraphQLError.newError()
.message("An unexpected error occurred.")
.errorType(ErrorType.DataFetchingException)
.build())
.build();
}
}Activating Your Custom Resolver
To make Spring GraphQL use your CustomExceptionResolver, you need to register it as a Spring @Bean in your application's configuration. This tells Spring to include it in the GraphQL execution chain.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import graphql.execution.DataFetcherExceptionHandler;
@Configuration
public class GraphQLConfig {
@Bean
public DataFetcherExceptionHandler customDataFetcherExceptionHandler() {
return new CustomExceptionResolver();
}
}See It in Action!
Let's run a simplified Spring Boot app. If you query for an item with an ID other than '1', our custom error resolver will catch the DemoResourceNotFoundException and format the error response with specific details in the extensions field.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import graphql.kickstart.tools.GraphQLQueryResolver;
import graphql.execution.DataFetcherExceptionHandler;
import graphql.execution.DataFetcherExceptionHandlerParameters;
import graphql.execution.DataFetcherExceptionHandlerResult;
import graphql.GraphQLError;
import graphql.error.ErrorType;
import java.util.HashMap;
import java.util.Map;
// Main Application Class
@SpringBootApplication
public class ErrorDemoApp {
public static void main(String[] args) {
SpringApplication.run(ErrorDemoApp.class, args);
}
@Bean
public GraphQLQueryResolver queryResolver() {
return new DemoQueryResolver();
}
@Bean
public DataFetcherExceptionHandler customDataFetcherExceptionHandler() {
return new CustomErrorResolver();
}
// Custom Exception
static class DemoResourceNotFoundException extends RuntimeException {
private final String resourceId;
public DemoResourceNotFoundException(String msg, String id) {
super(msg); this.resourceId = id;
}
public String getResourceId() { return resourceId; }
}
// Data Fetcher
@Component
static class DemoQueryResolver implements GraphQLQueryResolver {
public String getItem(String id) {
if ("1".equals(id)) {
return "Item Found: " + id;
}
throw new DemoResourceNotFoundException("Item not found", id);
}
}
// Custom Error Resolver
@Component
static class CustomErrorResolver implements DataFetcherExceptionHandler {
@Override
public DataFetcherExceptionHandlerResult onException(
DataFetcherExceptionHandlerParameters params) {
Throwable ex = params.getException();
if (ex instanceof DemoResourceNotFoundException) {
DemoResourceNotFoundException rnfEx = (DemoResourceNotFoundException) ex;
Map<String, Object> ext = new HashMap<>();
ext.put("code", "ITEM_NOT_FOUND");
ext.put("itemId", rnfEx.getResourceId());
GraphQLError error = GraphQLError.newError()
.message(rnfEx.getMessage())
.locations(params.getSourceLocation())
.extensions(ext)
.errorType(ErrorType.DataFetchingException)
.build();
return DataFetcherExceptionHandlerResult.newResult().error(error).build();
}
return DataFetcherExceptionHandlerResult.newResult()
.error(GraphQLError.newError()
.message("Unexpected error")
.errorType(ErrorType.DataFetchingException)
.build())
.build();
}
}
}Error Extensions for Context
The extensions map within a GraphQLError is a powerful feature. It allows you to include custom, machine-readable data (like errorCode, resourceId, or validation errors) that clients can use for advanced error handling logic, beyond just the human-readable message.
Best Practices for Errors
To ensure robust error handling in your GraphQL API:
- Be Specific: Use distinct custom exceptions for different error types.
- Hide Internals: Never expose raw stack traces or database errors in production environments.
- Consistent Format: Ensure your custom errors always follow a predictable structure.
- Client-Friendly: Provide clear messages and actionable codes for frontend logic.
Quick Check: Error Handling
Which interface is primarily used in Spring GraphQL to customize how Java exceptions are transformed into GraphQLError objects?
Recap: Custom Error Handling
We learned how to move beyond default GraphQL error messages by implementing custom exception handling in Spring Boot. You can create custom exceptions, use the DataFetcherExceptionResolver to catch them, and format precise GraphQLError objects with useful extensions. This improves API security, user experience, and client-side error management.
คำถามที่พบบ่อย
บทเรียน “การจัดการข้อผิดพลาดแบบกำหนดเองใน GraphQL” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การจัดการข้อผิดพลาดแบบกำหนดเองใน GraphQL” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส GraphQL APIs with Spring Boot ให้อัปเกรดเป็น CoddyKit PRO คอร์ส GraphQL APIs with Spring Boot มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การจัดการข้อผิดพลาดแบบกำหนดเองใน GraphQL”
นำการจัดการข้อยกเว้นแบบกำหนดเองมาใช้ และจัดรูปแบบการตอบกลับข้อผิดพลาดตามแนวทางปฏิบัติที่ดีของ GraphQL คุณปฏิบัติ GraphQL APIs with Spring Boot ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน GraphQL APIs with Spring Boot หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน GraphQL APIs with Spring Boot บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การจัดการข้อผิดพลาดแบบกำหนดเองใน GraphQL” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน GraphQL APIs with Spring Boot นี้ได้ไหม
ได้ บทเรียน GraphQL APIs with Spring Boot ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การจัดการข้อผิดพลาดแบบกำหนดเองใน GraphQL
- การยืนยันตัวตนด้วย Spring Security
- การอนุญาตด้วยคำสั่งกำกับและบริบท
- การจำกัดอัตราและการป้องกันความลึกของคำค้น