如何在 Relay 中捕获 GraphQL 错误信息?

How to capture the GraphQL error message in Relay?

在我的服务器上,我的 GraphQL 实现是使用 Flask、Graphene 和 SQLAlchemy。理想情况下,我希望能够简单地操纵 headers 和 return 401 错误响应,但是 GraphQL return 将所有内容都设为 200。

使用 flask.abort(401) 但是我至少能够获得此响应:

...
"errors": [
  {
    "message": "401 Unauthorized: The server could not verify that you are authorized to access the URL requested.  You either supplied the wrong credentials (e.g. a bad password), or your browser doesn't understand how to supply the credentials required.",
    "locations": [
      {
      "line": 11,
      "column": 3
      }
    ]
  }
]
...

我认为这是我此时可以处理的妥协。然而;因为没有什么可以这么简单...我不确定如何获取此错误消息。我读到 QueryRenderer 本身可能存在吞下这些 GraphQL 错误的问题,但我可以设法在 Environment 中的 Network object 中拦截它们。 . 基本上看起来像这样。

Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: {…}}
  __proto__: Promise[
    [PromiseStatus]]: "resolved"
    [[PromiseValue]]: Object
      data: {viewer: {…}}
      errors: Array(4)
        0: {locations: Array(1), message: "401 Unauthorized: The server could not verify that…nderstand how to supply the credentials required."}
        1: {locations: Array(1), message: "401 Unauthorized: The server could not verify that…nderstand how to supply the credentials required."}
        2: {locations: Array(1), message: "401 Unauthorized: The server could not verify that…nderstand how to supply the credentials required."}
        3: {locations: Array(1), message: "401 Unauthorized: The server could not verify that…nderstand how to supply the credentials required."}
      length: 4
      __proto__: Array(0)
    __proto__:Object

我真的不觉得在我的环境的网络层处理这个错误是管理这个问题的正确方法。 QueryRenderer 似乎最有意义...我基本上将其设置为唯一的真实来源。

顺便说一句,如果这不是很明显的话,我正在使用 Relay Modern。因此,很可能任何基于 Relay Classic 的解决方案都不适用。

编辑:撇开错误消息不谈,我这样做的动机是正确处理 JWT 令牌。我认为我正在寻找的解决方案与处理这些错误响应无关,而是扩展我对 JWT 的理解。

我没有意识到我的客户可以使用 jwt-decode 等包轻松解码 JWT,然后让我访问过期信息......最终我预见到某种形式的中间件实现,可以评估 JWT 上剩余的时间量以及是否需要刷新。

您可以在 onCompleted 回调中处理服务器错误:https://github.com/facebook/relay/pull/1938/files

我希望我能正确理解你的问题,你的 QueryRenderer 应该有一个包含错误的错误对象 https://facebook.github.io/relay/docs/query-renderer.html

render={({error, props}) => {
if (error) {
  return <div>{error.message}</div>;
} else if (props) {
  return <div>{props.page.name} is great!</div>;
}
return <div>Loading</div>;

environment.js 中,修改 fetch 函数,如果 errors 数组存在于 JSON 响应中,您会将其作为新的自定义错误抛出。这个抛出的错误将被传输到 QueryRenderer 在那里它将作为 error prop 可用。如果存在错误,则通过显示与错误相关的 UI 来处理它。

查看 GitHub 上的评论了解详细说明: https://github.com/facebook/relay/issues/1913#issuecomment-470541691