首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用django-graphql自定义错误?

如何使用django-graphql自定义错误?
EN

Stack Overflow用户
提问于 2021-02-03 01:18:33
回答 3查看 735关注 0票数 1

我正在使用Django和Graphene进行一个项目,使用django_graphql_auth库来处理身份验证,并要求我自定义在登录失败时收到的错误消息。我已经仔细阅读了文档如何做到这一点,它只提到了一个名为CUSTOM_ERROR_TYPE( 类型 )的设置,但我想我不知道如何使用它,或者它可能不像我想的那样工作。在我的档案里:

custom_errors.py

代码语言:javascript
复制
import graphene

class CustomErrorType(graphene.Scalar):
    @staticmethod
    def serialize(errors):
        return {"my_custom_error_format"}

settings.py

代码语言:javascript
复制
from .custom_errors import CustomErrorType

GRAPHQL_AUTH = {
    'CUSTOM_ERROR_TYPE': CustomErrorType,
}

user.py

代码语言:javascript
复制
class AuthRelayMutation(graphene.ObjectType):
    password_set = PasswordSet.Field()
    password_change = PasswordChange.Field()

    # # django-graphql-jwt inheritances
    token_auth = ObtainJSONWebToken.Field()
    verify_token = relay.VerifyToken.Field()
    refresh_token = relay.RefreshToken.Field()
    revoke_token = relay.RevokeToken.Field()
    unlock_user = UsuarioUnlock.Field()

class Mutation(AuthRelayMutation, graphene.ObjectType):
    user_create = UserCreate.Field()
    user_update = UserUpdate.Field()
    user_delete = UserDelete.Field()

schema = graphene.Schema(query=Query, mutation=Mutation)

然而,当我测试登录时,我仍然收到这样的消息:“请输入有效的凭据。”我该怎么做才能改变这个信息?

更新

代码语言:javascript
复制
class ObtainJSONWebToken(
    RelayMutationMixin, ObtainJSONWebTokenMixin, graphql_jwt.relay.JSONWebTokenMutation
):
    __doc__ = ObtainJSONWebTokenMixin.__doc__
    user = graphene.Field(UserNode)
    days_remaining = graphene.Field(graphene.String, to=graphene.String())
    unarchiving = graphene.Boolean(default_value=False)

    @classmethod
    def resolve(cls, root, info, **kwargs):
        user = info.context.user

        # Little logic validations

        unarchiving = kwargs.get("unarchiving", False)
        return cls(user=info.context.user, days_remaining=days_remaining)
        

    @classmethod
    def Field(cls, *args, **kwargs):
        cls._meta.arguments["input"]._meta.fields.update(
            {"password": graphene.InputField(graphene.String, required=True)}
        )
        for field in app_settings.LOGIN_ALLOWED_FIELDS:
            cls._meta.arguments["input"]._meta.fields.update(
                {field: graphene.InputField(graphene.String)}
            )
        return super(graphql_jwt.relay.JSONWebTokenMutation, cls).Field(*args, **kwargs)
EN

回答 3

Stack Overflow用户

发布于 2021-02-08 14:51:16

我也有过同样的问题。我找到并引用了这个GitHub线程:https://github.com/flavors/django-graphql-jwt/issues/147 --它有点过时了,但是我对它进行了调整,它起了作用:

代码语言:javascript
复制
import graphql_jwt
from graphql_jwt.exceptions import JSONWebTokenError


class CustomObtainJSONWebToken(ObtainJSONWebToken):
    @classmethod
    def mutate(cls, *args, **kwargs):
        try:
            return super().mutate(*args, **kwargs)
        except JSONWebTokenError:
            raise Exception('Your custom error message here')
票数 0
EN

Stack Overflow用户

发布于 2021-09-26 07:08:45

我也遇到了这个问题,但是由于这条线graphql_auth/bases.pydjango-graphql-auth库中,您必须将settings.py文件中的类指定为字符串,以便使用自定义错误。这似乎解决了我的问题。

例如,我有:

代码语言:javascript
复制
GRAPHQL_AUTH = {
    'CUSTOM_ERROR_TYPE': 'accounts.custom_errors.CustomErrorType'
}

(其中CustomErrorType是一个类似于您在最初的文章中指出的类)

票数 0
EN

Stack Overflow用户

发布于 2022-06-26 18:21:01

通过使用ErrorType提供的graphene_django错误格式,我修改了上面的代码。

代码语言:javascript
复制
import graphene
import graphql_jwt

from ..types import UserType
from graphene_django.types import ErrorType

from graphql_jwt.exceptions import JSONWebTokenError
from graphql_jwt.mixins import ResolveMixin

class CreateToken(graphql_jwt.JSONWebTokenMutation, ResolveMixin):
    user = graphene.Field(UserType)
    errors = graphene.List(ErrorType)

    @classmethod
    def mutate(cls, *args, **kwargs):
        try:
            return super().mutate(*args, **kwargs)
        except JSONWebTokenError as e:
            errors = ErrorType.from_errors({'username/password': [str(e)]})
            return cls(errors=errors)

    
    @classmethod
    def resolve(cls, root, info, **kwargs):
        return cls(user=info.context.user, errors=[])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66019921

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档