Coverage for docs_src/handling_errors/tutorial006.py: 100%

18 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-12-04 08:29 +0000

1from fastapi import FastAPI, HTTPException 1abcdefg

2from fastapi.exception_handlers import ( 1abcdefg

3 http_exception_handler, 

4 request_validation_exception_handler, 

5) 

6from fastapi.exceptions import RequestValidationError 1abcdefg

7from starlette.exceptions import HTTPException as StarletteHTTPException 1abcdefg

8 

9app = FastAPI() 1abcdefg

10 

11 

12@app.exception_handler(StarletteHTTPException) 1abcdefg

13async def custom_http_exception_handler(request, exc): 1abcdefg

14 print(f"OMG! An HTTP error!: {repr(exc)}") 1hijklmn

15 return await http_exception_handler(request, exc) 1hijklmn

16 

17 

18@app.exception_handler(RequestValidationError) 1abcdefg

19async def validation_exception_handler(request, exc): 1abcdefg

20 print(f"OMG! The client sent invalid data!: {exc}") 1opqrstu

21 return await request_validation_exception_handler(request, exc) 1opqrstu

22 

23 

24@app.get("/items/{item_id}") 1abcdefg

25async def read_item(item_id: int): 1abcdefg

26 if item_id == 3: 1vhwixjykzlAmBn

27 raise HTTPException(status_code=418, detail="Nope! I don't like 3.") 1hijklmn

28 return {"item_id": item_id} 1vwxyzAB