Exception Handler
noun
say it: “ik-SEP-shun HAND-ler” /ɪkˈsɛpʃən ˈhændlər/
In FastAPI, a function registered for one kind of exception that turns it into the answer sent back, such as a 404 with a JSON body, whichever route raised it.
What is an exception handler in FastAPI?
An exception handler is a function registered with @app.exception_handler(SomeError). Whenever that exception
reaches FastAPI from any route, FastAPI calls the handler with the request and the exception, and sends the answer it
returns, such as a 404 with a JSON body. The routes raise; one place decides the answer.
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
class TicketNotFound(Exception):
pass
app = FastAPI()
@app.exception_handler(TicketNotFound)
def ticket_not_found(request: Request, exc: TicketNotFound):
return JSONResponse(status_code=404, content={"detail": "No repair ticket with that number"})
@app.get("/tickets/{ticket_id}")
def get_ticket(ticket_id: int):
raise TicketNotFound()
response = TestClient(app).get("/tickets/12")
print(response.status_code, response.json()) # 404 {'detail': 'No repair ticket with that number'}
In a sentence
- “Dev registered an exception handler with @app.exception_handler(StatusChangeNotAllowed) to answer 409.”
- “One exception handler for TicketNotFound gives every route the same 404, so none of them builds it by hand.”
Level: Journeyman · More FastAPI terms at this level
Updated