PAYATHON 2026

如何在 strawberry 和 Django 中隐藏 GraphQL exceptions?

排障赵师傅

结论

在 Strawberry 的 Schema 层覆盖 process_errors(),让“预期错误”不再进入日志系统,同时保持 GraphQL 的执行结果不变。

Resolver 可以继续抛出 GraphQLError。Strawberry 仍会将它放入响应顶层的 errors 字段,Apollo Client 也能正常识别,只是终端不会再输出这类错误的 traceback。

为什么之前的处理没有生效

终端中的 GraphQLError 由 Strawberry 在执行 GraphQL 后主动记录,并非 Django 捕获了未处理的 HTTP 异常。

执行流程大致如下:

  1. Resolver 抛出异常。
  2. GraphQL 执行器捕获异常,并生成 ExecutionResult.errors。
  3. Strawberry 调用 Schema 的 process_errors() 记录错误。
  4. 扩展的 on_operation() 要等到 yield 之后才能读取结果。

等到 on_operation() 修改 result.errors 时,日志通常已经输出。

GraphQLView.report_errors() 也不是这条日志链路的可靠控制点。错误记录发生在 Schema 执行层,覆盖 View 方法可能不会影响终端输出。

推荐方案:自定义 Schema

建议定义一个专门表示“可预期业务错误”的异常,以免过滤范围过大,连真正的程序错误也被隐藏。

from graphql import GraphQLError


class ExpectedGraphQLError(GraphQLError):
    """可以安全返回给客户端,并且不需要输出 traceback 的业务错误。"""

在 resolver 中抛出该异常:

from .errors import ExpectedGraphQLError


@strawberry.mutation
def register(
    self,
    name: str,
    email: str,
    password: str,
) -> bool:
    if user_with_email_exists(email):
        raise ExpectedGraphQLError(
            "Email already in use.",
            extensions={"code": "BAD_USER_INPUT"},
        )

    create_user(name=name, email=email, password=password)
    return True

然后继承 strawberry.Schema,覆盖 process_errors():

import strawberry
from graphql import GraphQLError

from .errors import ExpectedGraphQLError
from .queries import Query
from .mutations import Mutation


class CustomSchema(strawberry.Schema):
    def process_errors(self, errors, execution_context=None):
        unexpected_errors: list[GraphQLError] = []

        for error in errors:
            original_error = error.original_error

            if isinstance(original_error, ExpectedGraphQLError):
                continue

            unexpected_errors.append(error)

        if unexpected_errors:
            super().process_errors(
                unexpected_errors,
                execution_context,
            )


schema = CustomSchema(
    query=Query,
    mutation=Mutation,
)

这里的 process_errors() 只筛选需要写入日志的错误,不会删除 ExecutionResult.errors 中的内容。客户端仍会收到类似下面的响应:

{
  "data": null,
  "errors": [
    {
      "message": "Email already in use.",
      "locations": [
        {
          "line": 18,
          "column": 5
        }
      ],
      "path": [
        "register"
      ],
      "extensions": {
        "code": "BAD_USER_INPUT"
      }
    }
  ]
}

如果只想过滤所有显式抛出的 GraphQLError

如果项目规模较小,且能确认所有主动抛出的 GraphQLError 都是预期错误,也可以直接判断 GraphQLError:

import strawberry
from graphql import GraphQLError


class CustomSchema(strawberry.Schema):
    def process_errors(self, errors, execution_context=None):
        unexpected_errors = [
            error
            for error in errors
            if not isinstance(error.original_error, GraphQLError)
        ]

        if unexpected_errors:
            super().process_errors(
                unexpected_errors,
                execution_context,
            )

这种写法简单,但过滤范围较大。如果某段代码错误地抛出了普通 GraphQLError,它的 traceback 也会被隐藏。生产项目更适合使用自定义异常类型,或按照明确的 extensions.code 白名单过滤。

例如:

class CustomSchema(strawberry.Schema):
    EXPECTED_CODES = {
        "BAD_USER_INPUT",
        "UNAUTHENTICATED",
        "FORBIDDEN",
    }

    def process_errors(self, errors, execution_context=None):
        unexpected_errors = []

        for error in errors:
            code = (error.extensions or {}).get("code")

            if code in self.EXPECTED_CODES:
                continue

            unexpected_errors.append(error)

        if unexpected_errors:
            super().process_errors(
                unexpected_errors,
                execution_context,
            )

相比仅依赖字符串 code,自定义异常类型通常更不容易误判。

不建议完全关闭 Strawberry 日志

Django 的 LOGGING 配置也可以降低或关闭 strawberry.execution logger,但 TypeError、数据库异常和 resolver 中的真实缺陷通常也会随之被隐藏。例如:

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "loggers": {
        "strawberry.execution": {
            "handlers": [],
            "propagate": False,
        },
    },
}

如果应用没有通过其他监控系统收集异常,最好不要全局关闭日志。过滤预期错误并保留未知异常的 traceback,排查线上问题时会更方便。

还需要注意的地方

示例中的“邮箱已被使用”是业务校验错误,不属于 GraphQL query 语法错误,适合使用自定义 ExpectedGraphQLError。

真正的 GraphQL 解析或验证错误可能没有 original_error,例如查询了不存在的字段。因此,不能把 original_error is None 直接视为可以忽略,最好根据项目的日志需求单独处理。

响应脱敏和终端日志过滤需要分别处理。process_errors() 负责控制日志输出。如果还要将未知异常返回给客户端的消息统一替换为 "Internal server error",应通过单独的错误格式化或扩展逻辑完成,同时保留服务端日志。可覆盖的方法及其签名可能随 Strawberry 版本变化,请以项目已安装版本中 strawberry.Schema.process_errors 的签名为准。

备注:内容仅供参考。