首页 > 解决方案 > 当服务器关闭时 React-Apollo 捕获

问题描述

在我的带有节点服务器的 React ApolloGraphQL 应用程序中,我试图让它在我的节点服务器关闭时捕获错误。当节点服务器启动时,一切正常且正常... graphQL 错误被捕获并显示。但是当我停止节点服务器时,我会遇到无法避免的运行时错误。当节点服务器关闭时,服务器会以503 Service Unavailable响应和非 JSON 的 html 页面进行响应。

apollo 客户端是这样设置的:

const client = new ApolloClient({
  assumeImmutableResults: true,
  fetchOptions: {
    credentials: "include"
  },
  fetch: fetch,
  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}`);}
    response = {errors:null};
  },
  cache: new InMemoryCache({
    freezeResults: true,
    dataIdFromObject: obj => {
      let dataId = null;
      switch (obj.__typename) {
        default:
          dataId = defaultDataIdFromObject(obj);
      }
      return dataId;
    },
    cacheRedirects: {
      Query: {
        productVariant: (_, args, { getCacheKey }) => {
          const cacheKey = getCacheKey({ __typename: "ProductVariant", ...args });
          return cacheKey;
        }
      }
    },
  }),
});

带有此消息的上述onError块响应:

Error: Network error: JSON.parse: unexpected character at line 1 column 1 of the JSON data

我以这种方式设置了突变:

const [mutateVariant, {data, error, loading}] = useMutation(UPDATE_PRODUCT_META);

我这样称呼它:

mutateVariant({ variables: {inputM: {...buildMetaInput(editedData)} }, 
    errorPolicy: 'ignore', onError: (error) => Logger("Error:", error)});

你可以看到我已经尝试了不同errorPolicy的设置并添加了onError回调。

但我不断收到未处理的运行时错误,似乎无法捕捉和处理它们:

Unhandled Runtime Error

Error: Network error: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Call Stack
ApolloError           webpack-internal:///./node_modules/apollo-client/bundle.esm.js (76:28)
error                 webpack-internal:///./node_modules/apollo-client/bundle.esm.js (1041:48)
notifySubscription    webpack-internal:///./node_modules/zen-observable/lib/Observable.js (140:18)
onNotify              webpack-internal:///./node_modules/zen-observable/lib/Observable.js (179:21)
error                 webpack-internal:///./node_modules/zen-observable/lib/Observable.js (240:15)
error/<               webpack-internal:///./node_modules/apollo-client/bundle.esm.js (880:76)
error                 webpack-internal:///./node_modules/apollo-client/bundle.esm.js (880:27)
notifySubscription    webpack-internal:///./node_modules/zen-observable/lib/Observable.js (140:18)
onNotify              webpack-internal:///./node_modules/zen-observable/lib/Observable.js (179:21)
error                 webpack-internal:///./node_modules/zen-observable/lib/Observable.js (240:15)
error                 webpack-internal:///./node_modules/apollo-link-error/lib/bundle.esm.js (53:34)
notifySubscription    webpack-internal:///./node_modules/zen-observable/lib/Observable.js (140:18)
onNotify              webpack-internal:///./node_modules/zen-observable/lib/Observable.js (179:21)
error                 webpack-internal:///./node_modules/zen-observable/lib/Observable.js (240:15)
createHttpLink/</</<  webpack-internal:///./node_modules/apollo-link-http/lib/bundle.esm.js (92:26)

error从 useMutation 钩子返回的数据:

graphQLErrors: Array []
message: "Network error: JSON.parse: unexpected character at line 1 column 1 of the JSON data"
​networkError: {…}
​  ​bodyText: "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>503 Service 
  Unavailable</title>\n</head><body>\n<h1>Service Unavailable</h1>\n<p>The server is temporarily unable 
  to service your\nrequest due to maintenance downtime or capacity\nproblems. Please try again later.  
  </p>\n<p>Additionally, a 503 Service Unavailable\nerror was encountered while trying to use an 
  ErrorDocument to handle the request.</p>\n</body></html>\n"
  name: "ServerParseError"
​​  response: Object {  }
​​  statusCode: 503

我如何捕捉到这个错误?

标签: reactjsreact-hooksreact-apolloapollo-client

解决方案


mutateVariant 函数返回一个承诺。尝试在调用后添加一个 .catch() 。

mutateVariant().catch(() => {...});

推荐阅读