首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将Graphene-Django / Graphene-Python异常打印到控制台进行调试?

如何将Graphene-Django / Graphene-Python异常打印到控制台进行调试?
EN

Stack Overflow用户
提问于 2019-06-01 11:46:33
回答 1查看 640关注 0票数 0

当发生GraphQL错误时,我不容易知道它发生在哪里。我不得不花费不必要的时间来追踪它。如何在文本编辑器的控制台中打印回溯?

EN

回答 1

Stack Overflow用户

发布于 2019-06-01 12:20:56

我通过使用result.errors访问GraphQL错误、遍历列表并使用python的print_tb函数打印回溯来回答我自己的问题。

有没有人有不同的或者更好的方法呢?

print_graphql_errors函数的用法示例:

代码语言:javascript
复制
from django.conf.settings import DEBUG

result = schema.execute(
    mutation_str, context_value=request, variable_values=variable_values
)

if result.errors is None:
    return self.handle_success(result)
if DEBUG:
    print_graphql_errors(result.errors)

return self.handle_failure(result)

print_graphql_errors函数:

代码语言:javascript
复制
from traceback import print_tb
from django.conf.settings import DEBUG

def print_graphql_errors(errors, raise_error=False):
    if not DEBUG:
        raise Exception(
            'DevError: This function should not be called in production'
        )

    assert errors, 'DevError: The "errors" parameter cannot be None'
    print_after = []
    current_error = None

    print('######################################################################')
    print('Manually Generated Traceback (with the print_graphql_errors function):')
    print(f'There are {len(errors)} errors:')

    for i, error in enumerate(errors):
        print(f'{i + 1}) ', error)

    print('######################################################################')

    for error in errors:
        current_error = error
        # FYI: This object has these attributes: (example attribute values)
            # tb_frame <frame at 0x000002DDB844D548, file 'site-packages\\graphql\\execution\\executor.py', line 455, code resolve_or_error>
            # tb_lasti 16
            # tb_lineno 447
            # tb_next <traceback object at 0x000002DDBAFBA388>
        # print('error.locations:', error.locations)
        # print('error.positions:', error.positions)
        try:
            print_tb(error.stack)
        except AttributeError as e:
            print(e.__traceback__)
            print(f'Warning: An error occured while trying to print the traceback: {e}. It has the following attributes instead: {dir(error)}')
            print_after.append(error)

    if len(print_after):
        print('###################################################################')
        print(f'Number of errors without the "stack" attribute: {len(print_after)}')
        print('###################################################################')

    if raise_error:
        for error in print_after:
            raise error

        raise current_error
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56403709

复制
相关文章

相似问题

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