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

14 statements  

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

1from fastapi import FastAPI, Request 1abcde

2from fastapi.responses import JSONResponse 1abcde

3 

4 

5class UnicornException(Exception): 1abcde

6 def __init__(self, name: str): 1abcde

7 self.name = name 1abcde

8 

9 

10app = FastAPI() 1abcde

11 

12 

13@app.exception_handler(UnicornException) 1abcde

14async def unicorn_exception_handler(request: Request, exc: UnicornException): 1abcde

15 return JSONResponse( 1abcde

16 status_code=418, 

17 content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."}, 

18 ) 

19 

20 

21@app.get("/unicorns/{name}") 1abcde

22async def read_unicorn(name: str): 1abcde

23 if name == "yolo": 1abcde

24 raise UnicornException(name=name) 1abcde

25 return {"unicorn_name": name} 1abcde