石墨烯错误消息
Posted
技术标签:
【中文标题】石墨烯错误消息【英文标题】:Graphene errors messages 【发布时间】:2020-01-08 11:02:32 【问题描述】:我想知道是否可以翻译石墨烯提供的验证错误消息?例如:“未提供身份验证凭据”,如下面的代码示例所示。
"errors": [
"message": "Authentication credentials were not provided",
"locations": [
"line": 2,
"column": 3
]
],
"data":
"viewer": null
【问题讨论】:
本-温多克劳迪奥! Este site é voltado apenas a perguntas e respostas em Inglês。 Para usar o Português, peço que uses o Stack Overflow em Português 还在寻找答案? 【参考方案1】:创建自定义错误类型
import graphene
from graphene_django.utils import camelize
class ErrorType(graphene.Scalar):
@staticmethod
def serialize(errors):
if isinstance(errors, dict):
if errors.get("__all__", False):
errors["non_field_errors"] = errors.pop("__all__")
return camelize(errors)
raise Exception("`errors` should be dict!")
将其添加到您的突变中
class MyMutation(graphene.Mutation):
# add the custom error type
errors = graphene.Field(ErrorType)
form = SomeForm
@classmethod
def mutate(cls, root, info, **kwargs):
f = cls.form(kwargs)
if f.is_valid():
pass
else:
# pass the form error to your custom error type
return cls(errors=f.errors.get_json_data())
示例
django-graphql-auth 使用类似的错误类型,它的工作原理是这样的,例如用于注册:
mutation
register(
email:"skywalker@email.com",
username:"skywalker",
password1: "123456",
password2:"123"
)
success,
errors,
token,
refreshToken
应该返回:
"data":
"register":
"success": false,
"errors":
"password2": [
"message": "The two password fields didn’t match.",
"code": "password_mismatch"
]
,
"token": null,
"refreshToken": null
【讨论】:
@pedroben 可以加SomeForm
的例子吗,我不太懂表单怎么实现
this is a better answer你需要了解cls
以上是关于石墨烯错误消息的主要内容,如果未能解决你的问题,请参考以下文章