簡體   English   中英

GraphQL - 如何捕獲“內部” Apollo/GraphQL 錯誤 - Java Spring Boot

[英]GraphQL - How to catch "Internal" Apollo/GraphQL errors - Java Spring Boot

我開始使用 GraphQL 一周,但我還沒有找到如何捕獲“內部”GraphQL 錯誤,例如CoercingParseValueException 因為我們的前端使用這個端點來接收一些關於運輸的信息。 當架構或必需字段丟失時,GraphQL 本身會發送一個錯誤,該錯誤剛剛收到一條帶有任意字符串的消息,您必須在前端解析該消息才能理解此消息並向客戶端顯示正確的錯誤。

對於我們的項目,我們為自定義錯誤定義了一個錯誤模型。 此錯誤模型包含一個代碼字段,其中包含針對 NotFoundException、ValidationException 等每種情況的自定義代碼。

但是我怎樣才能從 GraphQL 中捕獲錯誤並修改它們呢?

方法:

@Component
public class GraphQLErrorHandler implements graphql.servlet.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;
    }

} 

對我不起作用。 ProcessErrors 它永遠不會被調用。 我正在使用 Spring Boot (Kickstarter 版本)

對於自定義錯誤,我正在使用已發布 10 天的新功能。

@Component("CLASSPATH TO THIS CLASS")
public class GraphQLExceptionHandler {

    @ExceptionHandler({NotFoundException.class})
    GraphQLError handleNotFoundException(NotFoundException e) {
        return e;
    }

    @ExceptionHandler(ValidationException.class)
    GraphQLError handleValidationException(ValidationException e) {
        return e;
    }
}

這種方法適用於自定義錯誤消息。 要使用此功能,我必須啟用 graphql-servlet 屬性exception-handlers-enabled並將其設置為 true。 盡管如此,即使使用 Exception.class 定義了 ExceptionHandler 注釋,這種方法也不會捕獲“內部”Apollo/GraphQL 錯誤。

也許可以幫我解決這個問題?

非常感謝

嘗試這個。 您應該為一般異常返回 ThrowableGraphQLError 類型

@ExceptionHandler(Exception::class)
fun handleException(e: Exception): ThrowableGraphQLError {
    log.error("{}", e)
    return ThrowableGraphQLError(e, "Internal Server Error")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM