You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ApolloClient的GraphQL调用中捕获403响应避免Pod崩溃?

解决GraphQL 403错误未被捕获导致Pod崩溃的问题

你的代码存在几个关键问题,导致403错误无法被正确捕获:

  • 混合使用async/await与.then/.catch:外层try-catch无法捕获.then()链的错误,且Apollo Client返回4xx/5xx状态码时会直接reject Promise,不会进入.then()分支,你的内部.catch()虽能捕获错误,但未彻底阻止错误引发的崩溃风险。
  • 错误检查逻辑无效:Apollo Client不会将HTTP错误放在response.error中,而是直接让Promise reject,所以.then()里的if(response.error)判断永远不会触发。

重构后的解决方案

统一使用async/await语法,用外层try-catch捕获所有错误,包括403:

const client = new ApolloClient({
  link: new HttpLink({
    uri: 'https://url/graphql',
    fetch,
    headers: {
      'csrf-tokens': tokens,
      Referer: header_referer,
    },
  }),
  queryDeduplication: false
})

export const getProperties = async () => {
  try {
    const response = await client.query({ query, variables });
    const data = response.data.properties;
    // 处理正常返回的数据
    return data;
  } catch (error) {
    console.log("getProperties error:", error);
    // 针对性处理403权限错误
    if (error.statusCode === 403) {
      console.log("处理403权限错误:可执行刷新令牌、返回默认数据等操作");
    }
    // 返回安全默认值,避免后续渲染崩溃
    return [];
  }
}

关键说明

  1. 移除.then()和内部.catch(),所有请求错误会直接进入外层catch块。
  2. Apollo Client的错误对象包含statusCode字段,可精准判断403错误并执行对应逻辑(如刷新权限令牌)。
  3. 捕获错误后返回默认值(如空数组),确保后续组件渲染有可用数据,避免Pod因未处理的渲染错误崩溃。

内容的提问来源于stack exchange,提问作者user12551649

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 07:45:35