[英]Python graphql exception handling: Is it expected to get errors array with 200 OK response?
根據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 -
顯示堆棧跟蹤似乎是有意的。 您可以在 GitHub 上查看討論。 為了防止鏈接失效,討論的基礎是graphql-core
庫基本上會吃掉石墨烯拋出的所有錯誤,並將它們放在results.errors
數組中,而不會將堆棧跟蹤打印到sys.stderr
。 通常,這是不需要的行為,因此它似乎在拉取請求中被更改了。
如果您仍想模仿該行為,可以查看此 StackOverflow 答案以擺脫堆棧跟蹤:您可以通過限制其深度來關閉跟蹤。 它仍然應該以這種方式顯示在results.errors
中; 但是請注意,這仍然會在控制台上打印錯誤消息,但不會打印堆棧跟蹤。
如果你想完全消除控制台上的錯誤和堆棧跟蹤(我不推薦這樣做),你需要在應用程序中某處的突變解析器之外捕獲異常,以便錯誤仍然顯示在results.errors
數組中。 例如,您可以在 Flask 應用程序最初運行時執行此操作(盡管在這種情況下 scope 可能太大)。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.