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

问题描述 投票:1回答:3

在我的服务器上,我的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-decode等软件包来解码JWT,然后我可以访问到期信息...最终我预见到了某种形式的中间件实现可以评估JWT剩余的时间以及是否需要刷新。

graphql relay graphene-python relaymodern
3个回答
1
投票

您可以在qazxsw poi回调中处理服务器错误:qazxsw poi


1
投票

我希望我正确地理解你的问题,你的QueryRenderer应该有一个错误对象,它会产生错误onCompleted

https://github.com/facebook/relay/pull/1938/files

0
投票

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>; 函数,这样如果在JSON响应中存在environment.js数组,则会将其作为新的自定义错误抛出。这个引发的错误将被传送到fetch,它将作为errors道具提供。如果存在错误,则通过显示与错误相关的UI来处理它。

有关详细解释,请参阅GitHub上的这条评论:QueryRenderer

© www.soinside.com 2019 - 2024. All rights reserved.