【问题标题】:How to handle properly handle graphene error?如何正确处理石墨烯错误?
【发布时间】:2019-12-30 09:25:14
【问题描述】:

我在graphene-django的早期。

我有这样的Mutation

class DeleteObjection(graphene.Mutation):
    """
    1. Authorized User only
    2. His own `Objection` only
    3. Be able to delete only `Hidden type Objection`
    """
    ok = graphene.Boolean()

    class Arguments:
        id = graphene.ID()

    @classmethod
    def mutate(cls, root, info, **kwargs):
        tmp = {
            **kwargs,
            'created_by': info.context.user,
            'hidden': True
        }
        obj = Objection.objects.get(**tmp)
        obj.delete()
        return cls(ok=True)

res 就像我预期的那样处理。它是200,在控制台之后出现转发错误

{
  "errors": [
    {
      "message": "Objection matching query does not exist.",
      "locations": [
        {
          "line": 131,
          "column": 3
        }
      ],
      "path": [
        "deleteObjection"
      ]
    }
  ],
  "data": {
    "deleteObjection": null
  }
}

问题:
在我的Python 服务器控制台上。我看到错误已引发

Testing started at 16:01 ...
/Users/sarit/.pyenv/versions/multy_herr/bin/python "/Users/sarit/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/193.5662.61/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_test_manage.py" test multy_herr.objections.tests_jwt.UsersTest.test_authorized_user_delete_non_exist_objection /Users/sarit/mein-codes/multy_herr
Creating test database for alias 'default'...
System check identified no issues (0 silenced).

Traceback (most recent call last):
  File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.8/site-packages/promise/promise.py", line 489, in _resolve_from_executor
    executor(resolve, reject)
  File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.8/site-packages/promise/promise.py", line 756, in executor
    return resolve(f(*args, **kwargs))
  File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.8/site-packages/graphql/execution/middleware.py", line 75, in make_it_promise
    return next(*args, **kwargs)
  File "/Users/sarit/mein-codes/multy_herr/multy_herr/objections/grapheql/mutations.py", line 36, in mutate
    obj = Objection.objects.get(**tmp)
  File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.8/site-packages/django/db/models/query.py", line 415, in get
    raise self.model.DoesNotExist(
graphql.error.located_error.GraphQLLocatedError: Objection matching query does not exist.

Destroying test database for alias 'default'...


Process finished with exit code 0

问题:
我讨厌Python 控制台中的错误。因为它会在崩溃分析中报警,我认为它是一个糟糕的代码

尝试:
1.添加try - exception并再次提出

    @classmethod
    def mutate(cls, root, info, **kwargs):
        tmp = {
            **kwargs,
            'created_by': info.context.user,
            'hidden': True
        }
        try:
            obj = Objection.objects.get(**tmp)
        except Exception as err:

            raise Exception
        else:
            obj.delete()
            return cls(ok=True)

我得到了不满意的结果

res.data
Out[3]: OrderedDict([('deleteObjection', None)])
res.errors
Out[4]: [graphql.error.located_error.GraphQLLocatedError('')]
  1. 自定义我自己的class attribute
class DeleteObjection(graphene.Mutation):
    """
    1. Authorized User only
    2. His own `Objection` only
    3. Be able to delete only `Hidden type Objection`
    """
    ok = graphene.Boolean()
    errors = graphene.List(graphene.String)

    class Arguments:
        id = graphene.ID()

    @classmethod
    def mutate(cls, root, info, **kwargs):
        tmp = {
            **kwargs,
            'created_by': info.context.user,
            'hidden': True
        }
        try:
            obj = Objection.objects.get(**tmp)
        except Exception as err:
            return cls(ok=False, errors=[err])
        else:
            obj.delete()
            return cls(ok=True)

errors 不来回应

res.data
Out[3]: OrderedDict([('deleteObjection', OrderedDict([('ok', False)]))])
res.errors

问题:
如何在我的Python 控制台上抑制错误并遵循graphene-django 中的常见Exception

【问题讨论】:

    标签: python django exception graphene-django


    【解决方案1】:

    这是我如何处理 Graphene-Django 中的错误。

    class CreateBlog(graphene.Mutation):
       class Arguments:
          input = BlogInputType(required=True)
    
       ok = graphene.Boolean()
       blog = graphene.Field(BlogType)
       errors = graphene.Field(BlogErrorsInputType)
    
       @staticmethod
       def mutate(root, info, input):
          form = CreateBlogForm(data=input)
          if form.is_valid():
             blog = form.save()
             return CreateBlog(ok=True, blog=blog, errors=form.errors)
          return CreateBlog(ok=False, errors=form.errors)
    

    查看here 的详细信息。

    【讨论】:

      猜你喜欢
      • 2020-05-13
      • 2020-01-08
      • 2017-03-18
      • 2020-09-19
      • 2019-12-20
      • 2017-05-11
      • 2022-01-24
      • 2019-01-23
      • 2017-05-13
      相关资源
      最近更新 更多