1

在我的服务器上,我的 GraphQL 实现使用了 Flask、Graphene 和 SQLAlchemy。理想情况下,我希望能够简单地操作标头并返回 401 错误响应,但 GraphQL 将所有内容都返回为 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 错误,但我可以设法Network在...中的对象中拦截它们Environment,基本上看起来像这样。

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-decodeJWT JWT 上剩余的时间以及是否需要刷新。

4

3 回答 3

1

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

详细解释见 GitHub 上的这条评论: https ://github.com/facebook/relay/issues/1913#issuecomment-470541691

于 2019-04-07T12:03:41.577 回答
1

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

于 2017-08-18T09:29:16.883 回答
1

我希望我能正确理解你的问题,你的 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>;
于 2017-08-22T15:54:57.607 回答