使用解析器时如何在graphql-spring-boot中引发多个验证错误?

Lou*_*ise 7 validation error-handling graphql graphql-java

我正在使用 graphql-spring-boot 库,并使用解析器对象来解析输入查询的值。

下面是一个例子:

@Component
public class BookResolver implements GraphQLQueryResolver {

    @Autowired
    private BookImpl bookImpl;

    @Autowired
    private GraphqlValidator validator;

    public GetBookOutput getBooks(GetBookQuery getBookQuery) {  

        validator.validateBookInputQuery(getBookQuery);

        GetBookOutput output = bookImpl.getBook(getBookQuery)

        return output;
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我想验证 getBookQuery,并在发送到客户端的响应中引发自定义错误。输入 getBookQuery 类型包含一串数字。

下面是我如何实现 GraphqlValidator 类:

@Component
public class GraphqlValidator {

    private static final String BOOK_NUMBER_REGEX = " *[0-9]+( *, *[0-9]+)* *";

    public void validateBookInputQuery(GetBookInputQuery getBookInputQuery) {
        String bookNumber = getBookInputQuery.getBookNumber();

        if (!isValidValueForRefVal(bookNumber, BOOK_NUMBER_REGEX)) {
            throw new GraphqlInvalidFieldException("Input type getBookInputQuery Invalid", "bookNumber", bookNumber);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在 validateBookInputQuery 函数中,我抛出了一个异常,它是从 GraphQLError 实现的:

@SuppressWarnings("serial")
public class GraphqlInvalidFieldException extends RuntimeException implements GraphQLError{

    private Map<String, Object> extensions = new HashMap<>();
    String message;

    public GraphqlInvalidFieldException(String message, String fieldname, String arg) {
        //super(message);
        this.message = message;
        extensions.put(fieldname, arg);
    }

    @Override
    public List<SourceLocation> getLocations() {
        return null;
    }

    @Override
    public Map<String, Object> getExtensions() {
        return extensions;
    }

    @Override
    public ErrorType getErrorType() {
        return null;
    }

    @Override 
    public String getMessage() {
        return message;
    }

}
Run Code Online (Sandbox Code Playgroud)

通过这样做,我能够验证单个字段并将自定义错误消息发送到客户端。但是,在更复杂的场景中,输入类型 GetBookQuery 不仅包含 bookNumber,还包含 bookName 和 Author。换句话说,输入字段将包含多个需要验证的字段。我希望能够验证所有字段并将所有错误组合在一起并立即将它们发送给客户端。有人请帮我吗?

geg*_*geg -1

当您运行验证时,验证器可以将错误(字段和描述)添加到列表中,然后将其传递到最后的异常中,如果列表不为空,则抛出异常。