gpt4 book ai didi

graphene-python - 如何为 Graphite 烯/django-graphene 中的错误返回自定义 JSON 响应?

转载 作者:行者123 更新时间:2023-12-04 15:39:40 26 4
gpt4 key购买 nike

我想将状态字段添加到错误响应中,而不是这样:

{
"errors": [
{
"message": "Authentication credentials were not provided",
"locations": [
{
"line": 2,
"column": 3
}
]
}
],
"data": {
"viewer": null
}
}

应该是这样的:
{
"errors": [
{
"status": 401, # or 400 or 403 or whatever error status suits
"message": "Authentication credentials were not provided",
"locations": [
{
"line": 2,
"column": 3
}
]
}
],
"data": {
"viewer": null
}
}

我发现我只能通过在解析器中引发异常来更改消息: raise Error('custom error message') ,但如何添加字段?

代码示例:
class Query(UsersQuery, graphene.ObjectType):
me = graphene.Field(SelfUserNode)

def resolve_me(self, info: ResolveInfo):
user = info.context.user
if not user.is_authenticated:
# but status attr doesn't exist...
raise GraphQLError('Authentication credentials were not provided', status=401)
return user

最佳答案

更新默认 GraphQLView具有以下内容:

from graphene_django.views import GraphQLView as BaseGraphQLView


class GraphQLView(BaseGraphQLView):

@staticmethod
def format_error(error):
formatted_error = super(GraphQLView, GraphQLView).format_error(error)

try:
formatted_error['context'] = error.original_error.context
except AttributeError:
pass

return formatted_error


urlpatterns = [
path('api', GraphQLView.as_view()),
]

这将寻找 context引发的任何异常中的属性。如果它存在,它将使用此数据填充错误。

现在,您可以为填充 context 的不同用例创建异常(exception)。属性。在这种情况下,您想将状态代码添加到错误中,这是您如何执行此操作的示例:

class APIException(Exception):

def __init__(self, message, status=None):
self.context = {}
if status:
self.context['status'] = status
super().__init__(message)

你会像这样使用它:

raise APIException('Something went wrong', status=400)

关于graphene-python - 如何为 Graphite 烯/django-graphene 中的错误返回自定义 JSON 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49349689/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com