You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django集成Sentry时如何配置忽略指定类型错误不上报

Sentry 忽略指定类别异常的配置方案

针对sentry-sdk 1.16.0版本,有两种成熟方案可以实现自定义异常类不上报的需求:

方案1:使用ignore_errors参数快速配置

这是最简单直接的方式,在初始化Sentry时传入ignore_errors参数,直接声明需要忽略的异常类型即可,修改后的初始化代码如下:

from os import getenv


SENTRY_URL = getenv('SENTRY_URL')

if SENTRY_URL:
    from sentry_sdk import init
    from sentry_sdk.integrations.django import DjangoIntegration
    from sentry_sdk.integrations.redis import RedisIntegration
    from sentry_sdk.integrations.celery import CeleryIntegration
    # 导入你自定义的CustomError异常类,替换成你实际的导入路径
    from your_project.exceptions import CustomError

    init(
        dsn=SENTRY_URL,
        integrations=[DjangoIntegration(), RedisIntegration(), CeleryIntegration()],
        traces_sample_rate=1.0,
        send_default_pii=True,
        debug=True,
        # 新增忽略异常配置
        ignore_errors=[
            CustomError,
            # 可追加其他需要忽略的异常类或异常匹配规则
        ]
    )

ignore_errors支持两类匹配规则:

  • 直接传入异常类:匹配到该类及其所有子类的异常时,会直接跳过上报
  • 传入字符串:按正则规则匹配异常的全限定类名,比如传入字符串"your_project.exceptions.CustomError"也能实现相同过滤效果,不需要提前导入异常类

方案2:通过before_send钩子实现灵活过滤

如果需要更复杂的过滤逻辑——比如不是所有CustomError都忽略,只过滤携带特定错误码、特定错误信息的CustomError,可以使用before_send回调自定义判断逻辑,示例代码如下:

from os import getenv


SENTRY_URL = getenv('SENTRY_URL')

def filter_sentry_errors(event, hint):
    exc_info = hint.get("exc_info")
    if exc_info:
        exc_type, exc_value, _ = exc_info
        # 判断异常类型为CustomError时终止上报
        if issubclass(exc_type, CustomError):
            # 可追加自定义判断逻辑,比如 if exc_value.err_code == 40001: 才过滤
            return None
    # 其余异常正常上报
    return event

if SENTRY_URL:
    from sentry_sdk import init
    from sentry_sdk.integrations.django import DjangoIntegration
    from sentry_sdk.integrations.redis import RedisIntegration
    from sentry_sdk.integrations.celery import CeleryIntegration
    from your_project.exceptions import CustomError

    init(
        dsn=SENTRY_URL,
        integrations=[DjangoIntegration(), RedisIntegration(), CeleryIntegration()],
        traces_sample_rate=1.0,
        send_default_pii=True,
        debug=True,
        before_send=filter_sentry_errors
    )

提示:你当前已经加载了CeleryIntegration,Celery异步任务中抛出的异常会自动沿用上述全局过滤规则,不需要额外为Celery单独配置过滤逻辑。

内容的提问来源于stack exchange,提问作者Vadim Beglov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 17:03:20