python runtime_error ai_generated partial

Exception in background task ignored: RuntimeError('task failed')

ID: python/starlette-background-task-exception-swallowed

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2024-12-04First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.30+ active — — —

Root Cause

A BackgroundTask raised an exception after the response was sent; Starlette logs it but the client already received 200.

generic

中文

BackgroundTask 在响应发送后抛出异常;Starlette 记录了它,但客户端已经收到 200。

Workarounds

  1. 85% success
    import logging
    logger = logging.getLogger(__name__)
    def task():
        try:
            do_work()
        except Exception:
            logger.exception('background failed')
            raise
  2. 90% success
    from celery import Celery
    celery = Celery('app')
    celery.send_task('do_work')

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Hides failures from monitoring; no retries or alerts.

  2. 85% fail

    Background tasks run after the response; the route already returned.