【问题标题】:How to catch 403 response inside graphql api call?如何在 graphql api 调用中捕获 403 响应?
【发布时间】:2023-01-24 21:39:43
【问题描述】:

我有一个服务器,它执行组件的渲染并在发出请求时返回 HTML,同时渲染服务器对特定组件执行 graphql 调用,有时会返回 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 {
    await client
      .query({query, variables})
      .then((response) => {
         const data = response.data.properties;
         if(response.error) {
           throw new Error("Error encountered");
         }
       }
      .catch((error) => {
         console.log("gettProperites error")
      })
   } catch (err) {
       console.log("Execution failed")
   }
}

我在 getProperties 函数中进行 graphql 调用,每当我收到 403 错误时,我的 pod 就会崩溃。我已将调用包装在 try-catch 块中,并在 .then() 中添加了一个额外的 if 条件,以检查响应中是否有任何错误。尽管如此,403 响应仍未被捕获并导致 pod 崩溃。

上面的代码是我正在运行的代码的整体结构,我删除了一些不需要的细节以保持它的小。

【问题讨论】:

  • 当您遇到来自您的服务器的 403 时,您是否捕获并抛出错误?

标签: javascript node.js reactjs express graphql


【解决方案1】:

尝试拦截器。 我只能告诉 vue,但我认为在反应中它非常相似:

const link = createUploadLink({ uri: '/graphql' });

const errors = onError(({ networkError }) => {
    if (networkError.statusCode === 403) {
      // do something with 404 response code like:
      router.push('/403');
    }
    else {
      // do something with any other error response code
    }
  })

const apolloClient = new ApolloClient({
  link:  errors.concat(link),
  ...
})

【讨论】:

    猜你喜欢
    • 2021-01-11
    • 2021-03-24
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2018-01-02
    • 1970-01-01
    相关资源
    最近更新 更多