4

根据https://www.howtographql.com/graphql-python/6-error-handling/中的文档,我用来raise GraphQLError在我的 Flask GraphQL 应用程序变异函数中显示错误,如下所示:

import graphene
from graphql import GraphQLError

from ...extensions import db
from ...models import User as UserModel
from ..types import User as UserType

class Update(graphene.Mutation):
    class Input:
        id = graphene.ID(required=True)
        # phone = graphene.String()
        name = graphene.String(required=False, default_value=None)
        # active = graphene.Boolean()

    Output = UserType

    @staticmethod
    def mutate(root, info, **kwargs):
        user = graphene.Node.get_node_from_global_id(info, kwargs.pop('id'))
        # print(info.context)
        # if not user:
        raise GraphQLError('eeee')
        # user.update(**kwargs)
        # db.session.commit()

        return user

我期望得到类似 400 状态码的东西,带有 graphql 错误 json 模式。但我得到 200 并且异常打印在带有回溯的控制台中。我在这里做错了吗?

An error occurred while resolving field Mutation.updateUser
Traceback (most recent call last):
  File "/.local/share/virtualenvs/Server-CvYlbWSB/lib/python3.7/site-packages/graphql/execution/executor.py", line 447, in resolve_or_error
    return executor.execute(resolve_fn, source, info, **args)
  File "/.local/share/virtualenvs/Server-CvYlbWSB/lib/python3.7/site-packages/graphql/execution/executors/sync.py", line 16, in execute
    return fn(*args, **kwargs)
  File "/application/schema/mutation/user.py", line 40, in mutate
    raise GraphQLError('eeee')
graphql.error.base.GraphQLError: eeee
Traceback (most recent call last):
  File "/.local/share/virtualenvs/Server-CvYlbWSB/lib/python3.7/site-packages/graphql/execution/executor.py", line 447, in resolve_or_error
    return executor.execute(resolve_fn, source, info, **args)
  File "/.local/share/virtualenvs/Server-CvYlbWSB/lib/python3.7/site-packages/graphql/execution/executors/sync.py", line 16, in execute
    return fn(*args, **kwargs)
  File "/application/schema/mutation/user.py", line 40, in mutate
    raise GraphQLError('eeee')
graphql.error.located_error.GraphQLLocatedError: eeee

127.0.0.1 - - [17/Oct/2018 01:46:54] "POST /graphql? HTTP/1.1" 200 - 
4

1 回答 1

1

显示堆栈跟踪似乎是有意的。您可以在 GitHub 上查看讨论。以防万一链接失效,讨论的基础是该graphql-core库基本上会吃掉石墨烯抛出的所有错误并将它们放入results.errors数组中,而不会将堆栈跟踪打印到sys.stderr. 通常,这是不受欢迎的行为,因此它似乎在拉取请求中被更改。


如果您仍然想模仿这种行为,您可以查看此 StackOverflow 答案以摆脱堆栈跟踪:您可以通过限制其深度来关闭回溯。它仍应以results.errors这种方式显示;但是请注意,这仍然会在控制台上打印错误消息,但不会打印堆栈跟踪。

如果您想完全摆脱控制台上的错误和堆栈跟踪(我不推荐这样做),您需要在突变解析器之外的应用程序中的某处捕获异常,以使错误仍然显示在results.errors数组中。例如,您可以在 Flask 应用程序最初运行时执行此操作(尽管在这种情况下范围可能太大)。

try:
    app = Flask(__name__)
except GraphQLError as gqle:
    pass # ignore the error
except OtherErrorYouManuallyCall as oeymc:
    pass 
# Any other error will be thrown and show the stack trace
于 2018-10-18T19:46:35.920 回答