
今天开始使用commitizen
参考:https://zhuanlan.zhihu.com/p/100773495
今天在做项目时发现如下的代码会出现重复上报Sentry的问题
try:
...
except Exception as e:
capture_exception(e)
abort(500, description={
'success': False,
'code': 500,
'message': str(e),
'data': None
})

InteralServerError是由abort产生
abort(500, description={
'success': False,
'code': 500,
'message': str(e),
'data': None
})
OperationalError是由capture_exception产生
capture_exception(e)
我希望abort仅返回给客户端,不上报给Sentry
这时我想到了sentry_sdk.init里的before_send参数
def before_send(event, hint):
print(hint)
return event
sentry_sdk.init(
dsn=config.dsn,
server_name=config.sentry_server_name,
integrations=[FlaskIntegration()],
traces_sample_rate=config.traces_sample_rate,
environment=config.sentry_environment,
release=config.release,
before_send=before_send
)
打印出hint

可以看到hint是个字典,我们可以通过exc_info来进行过滤
最终代码为:
def before_send(event, hint):
if isinstance(hint['exc_info'][1], werkzeug.exceptions.InternalServerError):
return None
else:
return event
sentry_sdk.init(
dsn=config.dsn,
server_name=config.sentry_server_name,
integrations=[FlaskIntegration()],
traces_sample_rate=config.traces_sample_rate,
environment=config.sentry_environment,
release=config.release,
before_send=before_send
)
参考:
https://github.com/getsentry/sentry-python/issues/149#issuecomment-1056642777
Sentry 事件过滤:阻止特定错误上报

本文介绍了如何使用sentry_sdk的before_send参数来过滤上报到Sentry的错误。当遇到InternalServerError和OperationalError重复上报的问题时,作者通过检查hint['exc_info'][1]类型,实现了只返回给客户端错误,不向Sentry上报。最终代码中,如果异常是InternalServerError,则在before_send回调中返回None,阻止上报。
1018

被折叠的 条评论
为什么被折叠?



