javascript - 如何在前端 apollo-client 上处理来自 Node/Koa 的后端错误

标签 javascript node.js reactjs koa apollo

我的前端使用 apollo-client,当后端在请求后返回错误时抛出异常。

当 Node 服务器收到请求时,我使用 koa 中间件检查请求 token 的有效性。如果 token 有效,则将请求转发到下一个中​​间件。如果 token 无效,我想向客户端返回 401 拒绝访问错误。为此,我遵循了 Koa 的错误文档 located here .

我写的错误处理中间件的代码:

function userIdentifier() {
  return async (ctx, next) => {
    const token = ctx.request.headers.authorization

    try {
      const payload = checkToken(token)
      ctx.user = {
        id: payload.userId,
        exp: payload.exp,
        iat: payload.iat,
      }
    } catch (error) {
      ctx.user = undefined
      ctx.throw(401, "access_denied")
      // throw new Error("access_denied")
    }

    await next()
  }
}

这似乎适用于后端,但不适用于前端。当前端收到此错误时,会发生 JavaScript 运行时错误。我不确定是什么原因造成的。

enter image description here

请注意,意外的“a”与 ctx.throw(401, "access_denied") 中的“a”相同。如果是 ctx.throw(401, "x"),则前端会显示“unexpected token x”。

发生错误的前端代码:

enter image description here

为了解决这个问题,我遵循了 Apollo's error handling documentation并使用了 apollo-link-error

const errorLink = onError(props => {
  const { graphQLErrors, networkError } = props
  console.log("ON ERROR", props)
  if (graphQLErrors)
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
      )
    )
  if (networkError) console.log(`[Network error]: ${networkError}`)
})

然后我组合所有链接并像这样创建 Apollo 客户端:

const link = ApolloLink.from([errorLink, authLink, httpLink])

export const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
})

apollo-link-error中调试log的输出如下:

enter image description here

相关文档

有人似乎有一个 identical error , 但未列出解决方案。

最佳答案

当我开始在后端使用这个库时,我发现错误在前端得到了正确处理:https://github.com/jeffijoe/koa-respond

仅使用 ctx.unauthenticated()

但我仍然想知道更多关于如何在没有插件帮助的情况下使用 koa 返回基于 json/对象的错误

关于javascript - 如何在前端 apollo-client 上处理来自 Node/Koa 的后端错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48309586/

相关文章:

javascript - 使用加载器在 PHP 中加载另一个页面,同时使用简单的 HTML 表单

javascript - 元素尺寸正在 DOM 中更新,但更改未显示 onresize

javascript - express.js 中的常用函数放在哪里?

javascript - React 中的无限渲染

javascript - 我们如何比较每个元素数组并根据值显示元素

javascript - Css 溢出隐藏所有内容。无法修改滚动条

node.js - 如何在 AWS Lambda 处理程序触发之前运行异步函数

python - 在由 Galaxy 托管的生产 meteor 应用程序中安装 Python 模块

reactjs - 在 react 中从父组件调用子组件方法

javascript - 从使用 React 和 Webpack 构建的网站的 url 中删除 .html 扩展名