您可以尝试在错误处理方法中抛出一些异常,例如
package my.company.graphql.error;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import graphql.GraphQLError;
import graphql.GraphQLException;
import graphql.servlet.core.GraphQLErrorHandler;
import graphql.validation.ValidationError;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component
public class GraphQLErrorHandlerImpl implements GraphQLErrorHandler {
@Override
public List<GraphQLError> processErrors(List<GraphQLError> graphQLErrors) {
return graphQLErrors.stream().map(this::handleGraphQLError).collect(Collectors.toList());
}
private GraphQLError handleGraphQLError(GraphQLError error) {
if (error instanceof GraphQLException) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "GraphQLException as GraphQLError...", (GraphQLException) error);
} else if (error instanceof ValidationError){
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ValidationError: " + error.getMessage());
} else {
log.error("Yet another GraphQLError...", error);
return error;
}
}
}
...除了您只会得到 400 状态代码,而在您的响应中仅此而已,因为当您在例如http:// 127.0.0.1:8080/graphql
只有在您的日志中,您才能看到堆栈跟踪:(这只是 GraphQL 查询中未使用片段的验证错误示例)
[2020-09-23 15:59:34.382]-[080-exec-2]-[INFO ]-[g.s.AbstractGraphQLHttpServlet]: Bad POST request: parsing failed
org.springframework.web.server.ResponseStatusException: 400 BAD_REQUEST "ValidationError: Validation error of type UnusedFragment: Unused fragment someUnusedFragment"
at my.company.graphql.error.GraphQLErrorHandlerImpl.handleGraphQLError(GraphQLErrorHandlerImpl.java:33) ~[classes/:na]
引入更复杂的 GraphQL 错误处理取决于您,但这只是测试和试验(我们也已经做了相当长的一段时间......)