簡體   English   中英

在GraphQL-SPQR中返回錯誤的正確方法

[英]Correct way to return errors in GraphQL-SPQR

目前,我拋出RuntimeException來返回GraphQL驗證錯誤。 它工作異常出色,但它會在我的日志中引發帶有大堆棧跟蹤的可怕錯誤。

在這里,您可以看到我正在檢查提交的新用戶注冊突變,以確保密碼彼此匹配並且電子郵件地址尚未使用。

在GraphQL SPQR Spring Boot Starter中執行此操作的正確方法是什么。

@GraphQLMutation (name="register")
public User register(@GraphQLArgument(name="firstname") String firstname, @GraphQLArgument(name="lastname") String lastname, @GraphQLArgument(name="email") String email, @GraphQLArgument(name="msisdn") String msisdn, @GraphQLArgument(name="password") String password, @GraphQLArgument (name="confirmPassword") String confirmPassword) {
    if (userRepo.findByEmail(email) != null) {
        throw new RuntimeException("User already exists");
    }

    if (!password.equals(confirmPassword)) {
        throw new RuntimeException("Passwords do not match");
    }

    User newUser = new User();
    //...
    return userRepo.save(newUser);
}

我不清楚您要問的是什么...但是我假設您想自定義要記錄的內容。

對於初學者,我建議使用像ValidationException這樣的專用異常類型,您可以用不同的方式捕獲和處理它。

至於日志記錄,它可能發生在grapqh-java中,因為SPQR本身不會記錄任何內容。 默認情況下,graphql-java使用SimpleDataFetcherExceptionHandler記錄在字段解析期間捕獲的異常

現在,您有兩個選擇,您可以在SPQR中注冊一個ResolverInterceptor ,以捕獲驗證異常並記錄所需的內容,並為用戶返回帶錯誤消息的DataFetcherResult 由於沒有驗證異常會冒充到graphql-java,因此DataFetcherExceptionHandler在這種情況下沒有任何事可做。

它看起來像:

public class ValidationInterceptor implements ResolverInterceptor {

    @Override
    public Object aroundInvoke(InvocationContext context, Continuation continuation) throws Exception {
        try {
            return continuation.proceed(context);
        } catch (ValidationException e) {
            log.warning(e);
            return DataFetcherResult.newResult()
                    .error(GraphqlErrorBuilder
                            .newError(context.getResolutionEnvironment().dataFetchingEnvironment)
                            .message(e.getMessage()) //the message for the user
                            .build());
        }
    }
}

此處查看答案,以獲取有關在Spring Boot中注冊自定義攔截器的說明。

另一個選擇是替換DataFetcherExceptionHandler graphql-java使用。 為此,您必須自己構造GraphQL對象並將其注冊為Bean。

@Bean
public GraphQL graphQL(GraphQLSchema schema) {
    GraphQL.Builder builder = GraphQL.newGraphQL(schema)
            .queryExecutionStrategy(new AsyncExecutionStrategy(customExceptionHandler))
            .mutationExecutionStrategy(new AsyncSerialExecutionStrategy(customExceptionHandler));
    return builder.build();
}

如果某個地方有Spring功能可用於托管bean的異常處理,我也不會感到驚訝。

暫無
暫無

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

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