如何处理我的graphQL API中的错误?我使用的是graphql-java-tools和graphql-spring-boot-starter。我创建了错误处理程序,但每次当异常被抛出时,我都会得到200响应。你能告诉我应该如何设置错误代码吗,例如400?
@Component
public class CustomGraphQLErrorHandler implements GraphQLErrorHandler {
@Override
public List<GraphQLError> processErrors(List<GraphQLError> list) {
return list.stream().map(this::getNested).collect(Collectors.toList());
}
private GraphQLError getNested(GraphQLError error) {
if (error instanceof ExceptionWhileDataFetching) {
ExceptionWhileDataFetching exceptionError = (ExceptionWhileDataFetching) error;
if (exceptionError.getException() instanceof GraphQLError) {
return (GraphQLError) exceptionError.getException();
}
}
return error;
}
}发布于 2020-06-03 00:06:31
当GraphQL服务器可以接受请求时,它将返回HTTP200(语法有效,服务器已启动...)。
如果发生错误,它将返回200并填充响应中的错误列表。
因此,在客户端,您将拥有:
发布于 2020-09-23 22:11:29
你可以尝试在你的错误处理方法中抛出一些异常。
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;
}
}
}servlet你只会得到400状态码,在你的响应中什么也得不到,因为当你在http://127.0.0.1:8080/graphql上和GraphQL servlet(而不是servlet)交谈时,Spring不在这里处理抛出的异常
只有在您的日志中,您才能看到堆栈跟踪:(这只是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错误处理,但那只是测试和试用(正如我们已经做了相当长一段时间的那样……)
https://stackoverflow.com/questions/62085033
复制相似问题