【问题标题】:how to handle mutation error on apollo client?如何处理阿波罗客户端上的突变错误?
【发布时间】:2019-04-19 23:41:54
【问题描述】:

我正在尝试解决如何在 apollo 客户端处理抛出的 apollo-server 突变错误。

这是我对突变 (createCustomer) 的简化实现:

  Mutation: {
    createCustomer: async (_, { photoFile, customer }) => {
      const rootPath = path.resolve("./public");
      const customerPath = path.join(rootPath, "/photos/customers");
      try {
        const {
          dataValues: { customerID, firstname, lastname, email, phone }
        } = await models.Customer.create(customer);
        const customerUniqueDir = path.join(customerPath, 
         `${customerID}`);
       } catch (createCustomerError) {
       // throw new apollo-server error
        throw new UserInputError();
      }
    }
}

在客户端我收到以下错误: (第一个不是红色错误只是console.log在客户端的catch块中)

这个错误是由 apollo-link 抛出的:

这是来自服务器的响应:

这里是apollo-client的实现:

import { ApolloClient } from "apollo-client";
import { ApolloLink } from "apollo-link";
import { ErrorLink } from "apollo-link-error";
import { withClientState } from "apollo-link-state";
import { createUploadLink } from "apollo-upload-client";
import { ApolloProvider } from "react-apollo";
import { InMemoryCache } from "apollo-cache-inmemory";
import App from "./App";


const cache = new InMemoryCache({
  addTypename: false
});

const stateLink = withClientState({
  cache,
  resolvers: {
    Mutation: {}
  },
  defaults: {
    customers: { customers: [], count: 0 }
  }
});
const uploadLink = createUploadLink({ uri: "http://localhost:8000/graphql" });
const errorLink = new ErrorLink();

const client = new ApolloClient({
  link: ApolloLink.from([stateLink, errorLink, uploadLink]),
  cache,
  connectToDevTools: true
});

ReactDOM.render(
  <BrowserRouter>
    <ApolloProvider client={client}>
        <App />
    </ApolloProvider>
  </BrowserRouter>,
  document.getElementById("root")
);

有什么解决方案如何处理客户端上的突变错误?

感谢回答

【问题讨论】:

    标签: reactjs apollo-client apollo-server


    【解决方案1】:

    解决方案:

    错误出现在 apollo-link 中。所以我查看了我的 graphql-client 实现,我意识到我忘了使用 apollo-link-http 模块。

    所以我添加了以下代码行:

    import { HttpLink } from "apollo-link-http";
    
    const httpLink = new HttpLink({ uri: "http://localhost:8000/graphql" });
    
    const client = new ApolloClient({
      link: ApolloLink.from([stateLink,errorLink, httpLink, uploadLink]),
      cache,
      connectToDevTools: true
    });
    

    【讨论】:

      猜你喜欢
      • 2019-01-13
      • 2021-01-19
      • 2019-02-09
      • 2021-12-09
      • 2018-01-13
      • 2019-04-02
      • 2017-03-23
      • 2019-02-15
      • 2019-02-20
      相关资源
      最近更新 更多