django - Graphite 烯错误消息

标签 django graphql graphene-django

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

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

最佳答案

创建自定义错误类型

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
    }
  }
}

关于django - Graphite 烯错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57807244/

相关文章:

python - 未知命令 : 'clearsessions'

python - 是否可以使用 DJango 运行 ubuntu 终端命令

node.js - 字符串列表的变异变量 "$_v0_data"得到无效值 Graphql Node.js

django - 如何有条件地记录 graphene-django 中的异常?

django - graphene-django 为 DjangoFilterConnectionField 添加附加参数并将其传递给 get_queryset

python - 使用 Oracle 11g 数据库问题配置 django

python - 清除 Django 中的特定缓存

javascript - 如何将 GraphQL 服务器添加到预先存在的 SQL 数据库中?

java - 从 GraphQL-Java 返回错误

interface - 接口(interface)中包含的 Graphql 类型未添加到 graphene-django 中的模式