Python graphql异常处理

Python graphql exception handling

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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-error-json模式。但是我得到了200,并且异常也被打印在带有回溯的控制台中。我在这里做错什么了吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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 -


似乎有意显示堆栈跟踪。您可以在Github上查看讨论。为了防止链接死机,讨论的基本内容是,graphql-core库将从根本上消除由石墨烯抛出的所有错误,并将它们放入results.errors数组中,而不将堆栈跟踪打印到sys.stderr。一般来说,这是不需要的行为,因此它似乎在拉请求中被更改了。

如果您仍然想模拟这种行为,那么可以查看这个stackoverflow答案来消除堆栈跟踪:您可以通过限制跟踪的深度来关闭它。它仍然应该以这种方式显示在results.errors中;但是请注意,它仍然在控制台上打印错误消息,但不会打印堆栈跟踪。

如果您想完全消除控制台上的错误和堆栈跟踪(我不建议这样做),您需要在突变分解器之外的应用程序中的某个地方捕获异常,以便错误仍然显示在results.errors数组中。例如,您可以在最初运行flask应用程序时这样做(尽管在这种情况下范围可能太大)。

1
2
3
4
5
6
7
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