【问题标题】:How to handle error returning from a graphql backend on react admin?如何在反应管理员上处理从graphql后端返回的错误?
【发布时间】:2021-10-28 17:21:42
【问题描述】:

我想显示在提交用于创建新产品的 simpleForm 时从后端收到的错误。

我的查询构建器代码:

       case 'CREATE':
                if (typeof resource !== 'undefined' && resource.type.name === 'Product'){
                    result = {
                        query: PRODUCT_CREATE_ONE,
                        variables: { input: params.data },
                        parseResponse: response => ({
                            data: response.data.productCreate.product,
                            errors: response.data.productCreate.errors,
                        }),
                    }
 
 
                };
 

我可以在第一次尝试时成功添加产品!但是当我尝试使用现有的唯一键添加它时,我得到了

TypeError: Cannot read property 'hasOwnProperty' of null
    at validateResponseFormat (validateResponseFormat.js:25)
    at performPessimisticQuery.js:42

我从服务器收到的内容:

{
  "data": {
    "productCreate": {
      "product": null,
      "errors": [
        {
          "message": "Product with this Slug already exists.",
          "__typename": "ProductError"
        }
      ],
      "__typename": "ProductCreate"
    }
  }
}

我所期待的是,当 errors[] 不为空时会显示带有错误消息的通知

有没有办法处理从后端收到的错误以及如何处理?

【问题讨论】:

  • 您使用的是 apollo 客户端?
  • 是的,我正在使用 apollo 客户端` const client = new ApolloClient({ link: httpLink, cache: new InMemoryCache(), defaultOptions, });`

标签: reactjs graphql react-admin


【解决方案1】:

我建议你使用来自阿波罗的ErrorLink

import { onError } from "@apollo/client/link/error";

// Log any GraphQL errors or network error that occurred
const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
      )
    );
  if (networkError) console.log(`[Network error]: ${networkError}`);
});

const client = new ApolloClient({
  link: from([errorLink, httpLink]),
  cache: new InMemoryCache()
});

来源:Apollo Error Link

这将在请求中发生错误并且您可以通过例如处理它时触发。一个错误边界。

【讨论】:

  • 感谢您的帮助 Dani,但它对我不起作用。我遇到同样的问题!当我提交表单时,这段代码没有加载
  • 对不起,我不明白
  • Graphql 服务器没有返回 graphqlErrors 或 nertworkError 因为我不想要这种行为!当他发现一个键已经存在错误时,graphql 返回一个 200 响应
  • 所以,这是 gql 查询的预期行为。它返回 200,因为 http 请求成功,但查询不成功。您必须处理错误链接或组件中的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-23
  • 1970-01-01
  • 2020-03-10
  • 2021-10-12
  • 2021-04-03
  • 2018-09-07
相关资源
最近更新 更多