如何捕获 Pyramid+SQLAlchemy 中任何地方发生的 OperationalError?

How to catch OperationalError that happened anywhere in Pyramid+SQLAlchemy?

我有一个典型的 Pyramid+SQLAlchemy+Postgres 应用程序。在压力测试中或在异常负载的时刻和 PG 中的 max_connections 设置较低时,可能会引发 OperationalException

OperationalError: (psycopg2.OperationalError) FATAL:  sorry, too many clients already

现在,显然我不想在任何地方都这样做:

try:
    DBSession.query(Item)...
except OperationalError as e:
    log.error(...)

是否有某种方法可以捕获此异常 "globally" 并加以妥善处理?

我的应用程序以典型的金字塔方式使用 ZopeTransactionExtension

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))

我设法开发了一个可以做到这一点的补间(示例):

def catch_pg_exc_tween_factory(handler, registry):
    def catch_pg_exc_tween_clos(request):
        response = None
        try:
            response = handler(request)
        except Exception as e:
            log.error('\n\n\n +++ problem: %s', e)
        return response
    return catch_pg_exc_tween_clos

奇怪的是,在 development.ini 中除了明确的补间排序外什么都没有起作用(over=under= 调优 config.add_tween 调用的数量似乎没有起作用) :

pyramid.tweens = pyramid_debugtoolbar.toolbar_tween_factory
                 pyramid.tweens.excview_tween_factory
                 pyramid_tm.tm_tween_factory
                 mypkg.util.tweens.catch_pg_exc_tween_factory