我的前端使用 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 运行时错误。我不确定是什么原因造成的。
请注意,意外的“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()
但我仍然想知道更多关于如何在没有插件帮助的情况下使用 koa 返回基于 json/对象的错误
关于javascript - 如何在前端 apollo-client 上处理来自 Node/Koa 的后端错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48309586/