【问题标题】:How do I make Apollo Client tell me where in my code the error happened?如何让 Apollo Client 告诉我错误发生在代码的哪个位置?
【发布时间】:2020-08-08 03:38:47
【问题描述】:

我正在学习 React/Apollo,当我引入错误时,我的 Chrome 控制台中出现了典型的红色异常。但是,对于 Apollo,它并没有像在 React 或其他框架中那样告诉我错误是从哪里在我的代码中开始的。当使用在多个组件中触发查询的钩子时,查找问题根源的速度非常慢。

您是否使用任何技巧来调试您的 Apollo 代码,或者您能否以某种方式改进错误反馈?

这是我看到的:

ApolloError.ts:46 Uncaught (in promise) Error: GraphQL error: User is not authenticated
    at new ApolloError (ApolloError.ts:46)
    at QueryManager.ts:1241
    at Object.next (Observable.js:322)
    at notifySubscription (Observable.js:135)
    at onNotify (Observable.js:179)
    at SubscriptionObserver.next (Observable.js:235)
    at observables.ts:12
    at Set.forEach (<anonymous>)
    at Object.next (observables.ts:12)
    at notifySubscription (Observable.js:135)
    at onNotify (Observable.js:179)
    at SubscriptionObserver.next (Observable.js:235)
    at httpLink.ts:142

【问题讨论】:

    标签: react-hooks react-apollo apollo-client react-apollo-hooks


    【解决方案1】:

    首先,我想解决您在问题中看到的具体错误。

    User is not authenticated 会向我表明这不是客户端的问题(很可能),并且您正在尝试进行需要身份验证的查询。您未通过身份验证的原因可能与客户端有关,但任何前端框架都几乎不可能告诉您问题出在哪里。

    就调试 apollo 客户端问题的一般技术而言?好吧,当使用@apollo/react-hooks 时,你会从钩子直接返回的值中得到关于错误的反馈。例如,使用 useQuery 挂钩:

    
    const Employee = () => {
        const { data, loading, error } = useQuery(LOAD_EMPLOYEE_DATA_QUERY);
    
        if (error) {
            console.error(error);
    
            throw error;
        }
    
       // ...
    }
    

    如果客户端或服务器出现问题,您将在 error 对象中获得有关该问题的反馈。这使得调试变得相当简单。

    有时候,事情并不那么简单。当出现 apollo 客户端问题时,我通常会关注的下一个地方是 Apollo 开发工具。它将向您显示进行了哪些查询及其结果。

    最后,如果这不起作用,那么我将开始挖掘网络选项卡以获取对/(insert your graphql endpoint here) 的 XHR 请求。如果有红色,那么您应该查看服务器的控制台输出。

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      这些错误实际上是当您运行 ApolloClient.query() 并且有未捕获的错误时。

      这就是我为处理它所做的。 (但理想情况下,您应该使用 useQuery)

      const apiClient = new ApolloClient({
        ... // Your ApolloClient options
      });
      
      const originalQuery = apiClient.query;
      apiClient.query = (...args) => {
        // Get the original stack trace instead to figure out where our uncaught error is
        const stackTrace = new Error().stack;
        return originalQuery(...args).catch(e => {
          e.stack = stackTrace;
          throw e;
        });
      };
      

      这样,当我获得堆栈跟踪时,它实际上就是我使用这个特定 Query() 的地方

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-09
        • 2011-03-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-10
        • 1970-01-01
        • 2019-06-12
        相关资源
        最近更新 更多