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

How to handle backend errors from Node/Koa on frontend apollo-client

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

当节点服务器收到请求时,我使用 koa 中间件检查请求令牌的有效性。如果令牌有效,则将请求转发到下一个中​​间件。如果令牌无效,我想 return 向客户端发送 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 运行时错误。我不确定是什么原因造成的。

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

发生错误的前端代码:

为了解决这个问题,我遵循了 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的输出如下:

相关文档

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

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

仅使用 ctx.unauthenticated()

但我仍然想知道更多关于如何在没有插件帮助的情况下 return json/object-based koa 错误