GraphQL 사용자 지정 오류 처리
사용자 지정 예외 처리를 구현하고 GraphQL 모범 사례에 따라 오류 응답의 형식을 지정합니다.
GraphQL 사용자 지정 오류 처리은(는) CoddyKit의 무료 GraphQL APIs with Spring Boot 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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 사용자 지정 오류 처리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 GraphQL APIs with Spring Boot 강의 전체를 잠금 해제할 수 있습니다. GraphQL APIs with Spring Boot 강의에는 총 4개의 강의가 포함되어 있습니다.
“GraphQL 사용자 지정 오류 처리”에서 뭘 배우나요?
사용자 지정 예외 처리를 구현하고 GraphQL 모범 사례에 따라 오류 응답의 형식을 지정합니다. 브라우저에서 직접 실행하는 실습 코드로 GraphQL APIs with Spring Boot을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
GraphQL APIs with Spring Boot을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 GraphQL APIs with Spring Boot은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“GraphQL 사용자 지정 오류 처리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 GraphQL APIs with Spring Boot 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 GraphQL APIs with Spring Boot 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- GraphQL 사용자 지정 오류 처리
- Spring Security를 활용한 인증
- 지시문과 컨텍스트를 활용한 인가
- 요청 빈도 제한과 쿼리 깊이 보호