Custom exception handlers don't work in TestClient
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.
Nevermind.
Fixed with
test_cli = TestClient(app, raise_server_exceptions=False)
Wow, just wasted an hour looking for this. maybe it should default as False because I expect testClient to assert as 500 error.
There is mention about raise_server_exception here: https://www.starlette.io/testclient/ that I missed that time
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