Coverage for docs_src / handling_errors / tutorial006_py310.py: 100%
18 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-12 18:15 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-12 18:15 +0000
1from fastapi import FastAPI, HTTPException 1abcd
2from fastapi.exception_handlers import ( 1abcd
3 http_exception_handler,
4 request_validation_exception_handler,
5)
6from fastapi.exceptions import RequestValidationError 1abcd
7from starlette.exceptions import HTTPException as StarletteHTTPException 1abcd
9app = FastAPI() 1abcd
12@app.exception_handler(StarletteHTTPException) 1abcd
13async def custom_http_exception_handler(request, exc): 1abcd
14 print(f"OMG! An HTTP error!: {repr(exc)}") 1efg
15 return await http_exception_handler(request, exc) 1efg
18@app.exception_handler(RequestValidationError) 1abcd
19async def validation_exception_handler(request, exc): 1abcd
20 print(f"OMG! The client sent invalid data!: {exc}") 1hij
21 return await request_validation_exception_handler(request, exc) 1hij
24@app.get("/items/{item_id}") 1abcd
25async def read_item(item_id: int): 1abcd
26 if item_id == 3: 1kelfmg
27 raise HTTPException(status_code=418, detail="Nope! I don't like 3.") 1efg
28 return {"item_id": item_id} 1klm