📝 Add a section on handling errors inside background tasks by tsayin4 · Pull Request #16467 · fastapi/fastapi · GitHub
Skip to content

📝 Add a section on handling errors inside background tasks - #16467

Open
tsayin4 wants to merge 1 commit into
fastapi:masterfrom
tsayin4:docs-background-task-error-handling
Open

tsayin4 wants to merge 1 commit into
fastapi:masterfrom
tsayin4:docs-background-task-error-handling

Conversation

@tsayin4

@tsayin4 tsayin4 commented Oct 6, 2026

Copy link
Copy Markdown

This picks up #14599, which the inactivity bot closed while I was away — my fault for going quiet. The
bot suggested opening a new PR, so here it is, rewritten rather than restored.

The gap: a background task that raises cannot change a response that has already been sent, and the
exception never reaches the path operation function. From the outside a failed task looks exactly like
a successful one. #2505, #2604 and #3589 all come back to that, and the tutorial does not mention it.

What changed since the earlier attempt, after reading how the rest of the docs are written:

  • the example moved into docs_src/background_tasks/tutorial003_py310.py and is referenced with
    {* ... *}, so it is covered by a test like the other examples rather than being an inline block
  • /// tip instead of !!! tip, which is what the other 37 files in the tutorial use
  • the heading is "Handle errors in the task", matching the sentence-case style of its neighbours
  • the section is shorter, and points at the existing Caveat rather than repeating it

Two tests in tests/test_tutorial/test_background_tasks/test_tutorial003.py: the example runs, and a
task that raises still returns 200 while the error reaches the log — which is the behaviour the section
is actually describing. 5 passed in that directory.

Happy to trim it further if it is more than you want in a tutorial page.

A task that raises cannot change a response that has already been sent, and the
exception never reaches the path operation function, so a failed task looks
identical to a successful one from the outside.

The example lives in docs_src with a test, and the section points at a task queue
for work that needs to survive a restart.
@codspeed

codspeed Bot commented Oct 6, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant