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