Graphql Mutation 出现内部服务器错误 500

时间:2021-01-04 09:44:09

标签: android kotlin graphql apollo

As you can see that this query is showing the correct error message

viewModelScope.launch {
            val req = RequestCodeMutation(phoneNumber)
            val response = try {
                ApolloClientManager
                    .apolloClient
                    .suspendMutate(req)
            }
            catch (e: ApolloException) {
                println(e.message)
                isError.value = true
                null
            }
            finally {
                loading.value = false
            }
            val requestCode = response?.data?.requestCode
            println(response?.errors)
}
suspend fun <D : Operation.Data, T, V : Operation.Variables> ApolloClient.suspendMutate(mutation: Mutation<D, T, V>): Response<T> =
    mutate(mutation).toDeferred().await()

这是我在服务器端的验证器。它在 Graphiql 上显示正确,但是,我无法在客户端收到此消息。

requestCode = async (resolve, source, args, context, info) => {
        let { phoneNumber } = args;

        phoneNumber = validator.trim(phoneNumber);
        Object.assign(args, { phoneNumber });

        if (!validator.isMobilePhone(phoneNumber)) {
            throw new UserInputError('Invalid phone number provided!');
        }

        return resolve(source, args, context, info);
    }

ApolloException.message 显示内部服务器错误,response?.errors 显示 nullresponse?.errors 不应该是 null 并显示在 GraphiQL 上显示的正确错误消息。

1 个答案:

答案 0 :(得分:0)

在您的 catch 块中,您可以基于 ApolloCall 构建一个新的 Response

请考虑以下事项:

import com.apollographql.apollo.api.Response
import com.apollographql.apollo.api.Error

fun <T> executeCall(call: ApolloCall<T>): Response<T> = try {
  apolloCall.toDeferred().await()
} catch (apolloException: ApolloException) {
  val error = Error(apolloException.message ?: "Unknown Error")
  Response.builder(apolloCall.operation()).errors(listOf(error)).build()
}

注意:我假设 ApolloClientManager.apolloClient.suspendMutate(req) 返回一个 ApolloCall<T> 实例。

然后你可以像这样使用这个函数:

val call =  ApolloClientManager.apolloClient.suspendMutate(RequestCodeMutation(phoneNumber))
val response = executeCall(call)

// check the response status code