starlette icon indicating copy to clipboard operation
starlette copied to clipboard

Custom exception handlers don't work in TestClient

Open em92 opened this issue 7 years ago • 4 comments

from starlette.applications import Starlette
from starlette.testclient import TestClient
from starlette.responses import PlainTextResponse


async def unhandled_exception_handler(request, e):
    print("hey")
    return PlainTextResponse("hello")


class App(Starlette):
    def __init__(self):
        super().__init__()
        self.add_exception_handler(Exception, unhandled_exception_handler)


app = App()


@app.route("/method1")
def http_method2(request):
    raise Exception


test_cli = TestClient(app)
print("caught", test_cli.get("/method1"))
print("end")

hey in exception handler is printed. caught and end are not printed.

If we just run in uvicorn instead of test client, browser returns hello as expected.

em92 avatar Feb 13 '19 05:02 em92

Nevermind.

Fixed with

test_cli = TestClient(app, raise_server_exceptions=False)

em92 avatar Feb 13 '19 05:02 em92

Wow, just wasted an hour looking for this. maybe it should default as False because I expect testClient to assert as 500 error.

quocble avatar Oct 29 '19 21:10 quocble

There is mention about raise_server_exception here: https://www.starlette.io/testclient/ that I missed that time

em92 avatar Oct 30 '19 00:10 em92

Has the default behavior for this changed recently?

With starlette==0.45.3, TestClient did not throw the exception from handler even without raise_server_exceptions=False. After upgrading to starlette==0.46.0, my tests started failing and I needed to add raise_server_exceptions=False

Cnoor0171 avatar Mar 21 '25 21:03 Cnoor0171