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

16 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.exceptions import RequestValidationError 1abcde

3from fastapi.responses import PlainTextResponse 1abcde

4from starlette.exceptions import HTTPException as StarletteHTTPException 1abcde

5 

6app = FastAPI() 1abcde

7 

8 

9@app.exception_handler(StarletteHTTPException) 1abcde

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

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

12 

13 

14@app.exception_handler(RequestValidationError) 1abcde

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

16 return PlainTextResponse(str(exc), status_code=400) 1abcde

17 

18 

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

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

21 if item_id == 3: 1abcde

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

23 return {"item_id": item_id} 1abcde