Quarkus中SmallRye GraphQL自定义错误消息不生效求助
GraphQL自定义异常消息不显示问题解决
问题根源
你的自定义异常同时继承RuntimeException并实现GraphQLError,但GraphQL Java(或Spring GraphQL)在捕获RuntimeException时,会将其包装为DataFetchingException,导致自定义的getMessage()被忽略,转而返回默认的"System error"。
解决方案
方案1:移除RuntimeException继承,仅实现GraphQLError
修改异常类,不再继承RuntimeException,让框架直接识别为GraphQLError,使用自定义消息:
public class SomeException implements GraphQLError { private final List<String> someErrors; private final String errorMessage; public SomeException(String message, List<String> someErrors) { this.errorMessage = message; this.someErrors = someErrors; } @Override public String getMessage() { return this.errorMessage; } @Override public ErrorClassification getErrorType() { return ErrorClassification.ValidationError; // 根据业务场景指定错误类型 } @Override public Map<String, Object> getExtensions() { return Collections.singletonMap("someErrors", someErrors); } @Override public List<SourceLocation> getLocations() { return null; } // 适配新版本GraphQL Java,指定描述信息映射到响应message字段 @Override public String getDescription() { return this.errorMessage; } }
方案2:保留RuntimeException,添加自定义异常处理器
如果必须继承RuntimeException,实现DataFetcherExceptionResolver手动处理自定义异常:
步骤1:编写异常处理器
@Component public class CustomExceptionResolver implements DataFetcherExceptionResolver { @Override public CompletableFuture<GraphQLError> resolveException(DataFetchingEnvironment env, Exception ex) { if (ex instanceof SomeException) { SomeException customEx = (SomeException) ex; GraphQLError error = new GraphQLError() { @Override public String getMessage() { return customEx.getErrorMessage(); } @Override public List<SourceLocation> getLocations() { return env.getField().getSourceLocation(); } @Override public ErrorClassification getErrorType() { return ErrorClassification.ValidationError; } @Override public Map<String, Object> getExtensions() { return Collections.singletonMap("someErrors", customEx.getSomeErrors()); } }; return CompletableFuture.completedFuture(error); } // 其他异常交给默认逻辑处理 return DataFetcherExceptionResolver.super.resolveException(env, ex); } }
步骤2:确保处理器被Spring扫描
确保CustomExceptionResolver类添加了@Component注解,且所在包被Spring组件扫描覆盖。
验证效果
修改完成后重启服务,抛出SomeException时,响应的message字段会显示自定义错误内容,extensions中的someErrors也会正常保留。
内容的提问来源于stack exchange,提问作者Parneet Raghuvanshi
相关产品推荐
相关产品推荐

