石墨烯错误消息

Cla*_*ros 7 django graphql graphene-django

我想知道是否可以翻译石墨烯提供的验证错误消息?例如:“未提供身份验证凭据”,如下面的代码示例所示。

{
  "errors": [
    {
      "message": "Authentication credentials were not provided",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ]
    }
  ],
  "data": {
    "viewer": null
  }
}
Run Code Online (Sandbox Code Playgroud)

ped*_*ern 4

创建自定义错误类型

\n\n
import graphene\nfrom graphene_django.utils import camelize\n\nclass ErrorType(graphene.Scalar):\n    @staticmethod\n    def serialize(errors):\n        if isinstance(errors, dict):\n            if errors.get("__all__", False):\n                errors["non_field_errors"] = errors.pop("__all__")\n            return camelize(errors)\n        raise Exception("`errors` should be dict!")\n
Run Code Online (Sandbox Code Playgroud)\n\n

将其添加到您的突变中

\n\n
class MyMutation(graphene.Mutation):\n\n    # add the custom error type\n    errors = graphene.Field(ErrorType)\n\n    form = SomeForm\n\n    @classmethod\n    def mutate(cls, root, info, **kwargs):\n        f = cls.form(kwargs)\n        if f.is_valid():\n            pass\n        else:\n            # pass the form error to your custom error type\n            return cls(errors=f.errors.get_json_data())\n
Run Code Online (Sandbox Code Playgroud)\n\n

例子

\n\n

django-graphql-auth使用类似的错误类型,它的工作原理如下,例如注册:

\n\n
mutation {\n  register(\n    email:"skywalker@email.com",\n    username:"skywalker",\n    password1: "123456",\n    password2:"123"\n  ) {\n    success,\n    errors,\n    token,\n    refreshToken\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

应该返回:

\n\n
{\n  "data": {\n    "register": {\n      "success": false,\n      "errors": {\n        "password2": [\n          {\n            "message": "The two password fields didn\xe2\x80\x99t match.",\n            "code": "password_mismatch"\n          }\n        ]\n      },\n      "token": null,\n      "refreshToken": null\n    }\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n