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

19 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-12 18:15 +0000

1from fastapi import FastAPI, HTTPException 1abcd

2from fastapi.exceptions import RequestValidationError 1abcd

3from fastapi.responses import PlainTextResponse 1abcd

4from starlette.exceptions import HTTPException as StarletteHTTPException 1abcd

5 

6app = FastAPI() 1abcd

7 

8 

9@app.exception_handler(StarletteHTTPException) 1abcd

10async def http_exception_handler(request, exc): 1abcd

11 return PlainTextResponse(str(exc.detail), status_code=exc.status_code) 1hij

12 

13 

14@app.exception_handler(RequestValidationError) 1abcd

15async def validation_exception_handler(request, exc: RequestValidationError): 1abcd

16 message = "Validation errors:" 1efg

17 for error in exc.errors(): 1efg

18 message += f"\nField: {error['loc']}, Error: {error['msg']}" 1efg

19 return PlainTextResponse(message, status_code=400) 1efg

20 

21 

22@app.get("/items/{item_id}") 1abcd

23async def read_item(item_id: int): 1abcd

24 if item_id == 3: 1khlimj

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

26 return {"item_id": item_id} 1klm