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

18 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1from fastapi import FastAPI, HTTPException 1abcde

2from fastapi.exception_handlers import ( 1abcde

3 http_exception_handler, 

4 request_validation_exception_handler, 

5) 

6from fastapi.exceptions import RequestValidationError 1abcde

7from starlette.exceptions import HTTPException as StarletteHTTPException 1abcde

8 

9app = FastAPI() 1abcde

10 

11 

12@app.exception_handler(StarletteHTTPException) 1abcde

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

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

15 return await http_exception_handler(request, exc) 1abcde

16 

17 

18@app.exception_handler(RequestValidationError) 1abcde

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

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

21 return await request_validation_exception_handler(request, exc) 1abcde

22 

23 

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

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

26 if item_id == 3: 1abcde

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

28 return {"item_id": item_id} 1abcde