0

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

4

1 回答 1

2

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

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

print_graphql_errors 函数的示例用法:

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 函数:

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
于 2019-06-01T04:20:55.933 回答