skip to content

In FastAPI's TestClient, what does raise_server_exceptions control, and how do you test the body of a 500 response?

level: middleimportance: should knowfreq 35%

answer

  1. default True
  2. only exceptions that escape the app
  3. handled errors stay responses
  4. the outermost error middleware re-raises
  5. the transport's flag has another name

basics

~20 s

raise_server_exceptions, True by default, re-raises an exception that escapes the app into the test instead of returning a 500. To assert on the 500 body, use TestClient(app, raise_server_exceptions=False); HTTPException and handled errors are ordinary responses either way.

solid answer

~30 s

By default `TestClient` re-raises any exception that escapes the app, so the test fails with the real traceback rather than a bare 500. That covers only unhandled errors: `HTTPException`, a `RequestValidationError` (422) and exceptions with their own `exception_handler` come back as ordinary responses. A catch-all `@app.exception_handler(Exception)` is the trap: Starlette's `ServerErrorMiddleware` sends its response and then re-raises, so the default client still raises. To assert on a 500 body, build `TestClient(app, raise_server_exceptions=False)` and you get the handler's response, or FastAPI's plain-text `Internal Server Error`. For `httpx.AsyncClient` the switch is `ASGITransport(raise_app_exceptions=False)`.

code

python · 23 lines
python
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    raise ValueError("price feed unavailable")


def test_error_propagates():
    client = TestClient(app)
    with pytest.raises(ValueError, match="price feed unavailable"):
        client.get("/items/1")


def test_error_as_500_response():
    client = TestClient(app, raise_server_exceptions=False)
    response = client.get("/items/1")
    assert response.status_code == 500
    assert response.text == "Internal Server Error"

go deeper

for a junior

Remember the default: an unhandled exception in the endpoint is raised in your test, and HTTPException still comes back as a normal response.

for a middle

Explain which errors are responses and which are re-raised, why a catch-all Exception handler still raises, and the matching ASGITransport flag.

for a senior

Use 500 tests to prove nothing internal leaks and that debug mode is off, while keeping re-raising on everywhere else so failures stay diagnosable.

for a principal

Make the team's error contract testable: one client for 500 tests, assertions on the envelope, and a rule against disabling re-raise to quiet flaky tests.

## What the flag does `raise_server_exceptions` is a `TestClient` constructor argument, **`True` by default**. When an exception escapes the FastAPI app during a request, the client re-raises it in the test, at the call site, with the original traceback. With `False`, the client returns whatever response the app sent, which for an unhandled error is a 500. The default exists because a bare 500 is a poor test failure: it tells you something broke, not what. Re-raising points straight at the failing line. ## Which errors reach the test Only exceptions that escape the app's handling are re-raised. Anything FastAPI or your code turns into a response is just a response: | What the endpoint raises | Default client | `raise_server_exceptions=False` | |---|---|---| | `HTTPException(status_code=404, ...)` | a 404 response | a 404 response | | Invalid input (`RequestValidationError`) | a 422 response | a 422 response | | A custom exception class with its own `exception_handler` | that handler's response | that handler's response | | An unhandled `ValueError` | `ValueError` raised in the test | a 500 response, body `Internal Server Error` | | An unhandled error, with a handler for `Exception` or `500` | the error raised in the test | the handler's 500 response | ## The catch-all handler trap The last row surprises people. A handler registered with `@app.exception_handler(Exception)` (or for status `500`) is not installed with the other handlers. Starlette passes it to **`ServerErrorMiddleware`**, the outermost layer of the app, which: 1. catches the exception, 2. calls your handler and **sends its response**, 3. then **re-raises the exception anyway**, so the server can log it. In production the client has already received your JSON 500 and the server logs the traceback. In a test with the default client, the re-raise wins: the test sees the exception, not the JSON body. So a test of a catch-all error envelope has to use `raise_server_exceptions=False`. ## Asserting on a 500 1. Build a dedicated client: `TestClient(app, raise_server_exceptions=False)`. Keep the default client for every other test. 2. Trigger the failure, for instance by making a dependency raise. 3. Assert on `response.status_code == 500` and on the body: your handler's JSON, or FastAPI's plain-text `Internal Server Error` when no handler is registered. 4. Assert that the body leaks nothing internal: no exception message, no traceback, no file paths. The last step is the defender's reason to test 500s at all. With `FastAPI(debug=True)`, the server-error middleware returns a traceback response instead, even when a catch-all handler is registered; that is useful locally and a leak anywhere else, so a test that pins the production body also catches debug mode left on. ## Reading the example The code example keeps both behaviours side by side: - `test_error_propagates` uses the default client and expects the endpoint's own `ValueError`, matched on its message, which is what a developer wants to see when the endpoint is broken by accident. - `test_error_as_500_response` builds a second client with `raise_server_exceptions=False` and asserts on what a caller receives: status 500 and the plain-text body `Internal Server Error`, with the exception's message nowhere in it. The two tests are not redundant. The first documents that the failure is a bug in the endpoint; the second documents the contract a caller sees when any bug happens. A suite that only has the second kind hides real failures behind a status code, and one that only has the first never checks what leaks to callers. ## The async equivalent `httpx.ASGITransport` has the same switch under a different name: **`raise_app_exceptions`**, also `True` by default. `ASGITransport(app=app, raise_app_exceptions=False)` returns the app's 500 response to an `AsyncClient`. Passing `raise_server_exceptions` to the transport is a `TypeError`: that keyword belongs to `TestClient`. ## When to keep the default - **Almost always.** Most tests expect success or a handled error, and an unexpected exception should fail loudly with its traceback. - Switch it off only in tests whose subject **is** the 500: the error envelope, logging, or that internals stay hidden. - Do not switch it off to make a flaky test pass: it hides the exception that explains the flakiness. - Keep the non-raising client in its own fixture or test module, named for its purpose, so a reader sees at once which tests expect a 500 and nobody reuses it by accident.

  • Why is raise_server_exceptions=True the better default for most FastAPI tests?
    An unexpected exception then fails the test at the call with its own traceback, instead of a 500 that you must reproduce to understand. Tests whose subject is the 500 itself opt out explicitly with a second client, so the intent is visible and the rest of the suite still fails loudly.
  • With raise_server_exceptions=False, what does a 500 test protect against in production?
    It pins the body a caller sees when something breaks: your error envelope, with no exception text, traceback or paths. It also catches `debug=True` left on, because the server-error middleware then returns a traceback response instead of your envelope or the plain `Internal Server Error`.

  • With the default TestClient, a crashing endpoint returns a 500 to assert on
  • HTTPException is re-raised into the test by default
  • A catch-all Exception handler stops TestClient from raising
  • raise_server_exceptions=False turns 422 validation errors into 500s
  • ASGITransport accepts raise_server_exceptions as well