Python graphql exception handling
根据https://www.howtographql.com/graphql-python/6-error-handling/中的文档,我使用
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上查看讨论。为了防止链接死机,讨论的基本内容是,
如果您仍然想模拟这种行为,那么可以查看这个stackoverflow答案来消除堆栈跟踪:您可以通过限制跟踪的深度来关闭它。它仍然应该以这种方式显示在
如果您想完全消除控制台上的错误和堆栈跟踪(我不建议这样做),您需要在突变分解器之外的应用程序中的某个地方捕获异常,以便错误仍然显示在
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 |