首页 > 解决方案 > React 上的 Apollo 客户端 - 如何检索错误信息?

问题描述

我在任何地方都找不到有关它的信息...

考虑这个非常简单的场景......

<Mutation mutation={LOGIN_MUTATION}>
            {(login, { data, loading, error }) => {
                if (error) {
                    console.log(error)
                }

我收到一条字符串错误消息,例如...

Error: GraphQL error: ERROR_INVALID_LOGIN_PROVIDER
at new ApolloError (bundle.umd.js:92)
at MutationData.onMutationCompleted (react-hooks.cjs.js:636)
at react-hooks.cjs.js:559
at tryCallOne (core.js:37)
at core.js:123
at JSTimers.js:289
at _callTimer (JSTimers.js:146)
at _callImmediatesPass (JSTimers.js:194)
at Object.callImmediates (JSTimers.js:458)
at MessageQueue.__callImmediates (MessageQueue.js:366)

我无法根据以这种方式形成的错误消息采取行动。例如,ERROR_INVALID_LOGIN_PROVIDER 可能是 ERROR_INVALID_PASSWORD... 我需要根据错误消息做出决定。但我只收到一个包含graphql错误的字符串,js中的模块和很多不重要的信息。有没有办法接收格式为 imn 的错误消息,我只能提取服务器错误?

标签: react-apollo

解决方案


这应该是可能的

您的示例中的错误应该是可能带有GraphQLErrors或NetworkError 的ApolloError

(login, { data, loading, error }) => {
            if (error) {
                if (error.graphQlErrors && error.graphQLErrors.length > 0) {
                    // There are graphQL errors and there may be multiple but its always an array.
                    // You should handle it properly

                     const { message } = error.graphQLErrors[0]
                     console.log(message) // e.g. ERROR_INVALID_LOGIN_PROVIDER

                 } else if (error.networkError) {
                    // There may be a network error
                     const { message } = error.networkError
                     console.log(message) // e.g. NetworkError when attempting to fetch resource.
                 }
        }

推荐阅读