Python graphql异常处理

时间:2018-10-16 22:36:31

标签: graphene-python flask-graphql graphql-python graphene-sqlalchemy

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

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

我期望得到带有graphql错误json模式的400状态代码。但是我得到了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 - 

1 个答案:

答案 0 :(得分:1)

似乎故意显示了堆栈跟踪。您可以查看discussion on GitHub。以防万一链接消失,讨论的基础是graphql-core库实际上将吞噬石墨烯抛出的所有错误并将它们放置在results.errors数组中,而无需将堆栈跟踪打印到{{1} }。通常,这是不想要的行为,因此似乎在请求请求中已对其进行了更改。


如果您仍然想模仿该行为,则可以查看以下StackOverflow答案以摆脱堆栈跟踪:You can turn off the traceback by limiting its depth。它仍然应该以这种方式显示在sys.stderr中;但是请注意,这仍然会在控制台上显示错误消息,但不会显示堆栈跟踪。

如果您想完全摆脱错误并在控制台上进行堆栈跟踪(我不推荐这样做),则需要在应用程序 ,以便使错误仍显示在results.errors数组中。例如,您可以在最初运行Flask应用程序时执行此操作(尽管在这种情况下范围可能太大)。

results.errors