Debian Codegraph @

docs_src/handling_errors/tutorial006_py310.py

raw
1 from fastapi import FastAPI, HTTPException
2 from fastapi.exception_handlers import (
3 http_exception_handler,
4 request_validation_exception_handler,
5 )
6 from fastapi.exceptions import RequestValidationError
7 from starlette.exceptions import HTTPException as StarletteHTTPException
8
9 app = FastAPI()
10
11
12 @app.exception_handler(StarletteHTTPException)
13 async def custom_http_exception_handler(request, exc):
14 print(f"OMG! An HTTP error!: {repr(exc)}")
15 return await http_exception_handler(request, exc)
16
17
18 @app.exception_handler(RequestValidationError)
19 async def validation_exception_handler(request, exc):
20 print(f"OMG! The client sent invalid data!: {exc}")
21 return await request_validation_exception_handler(request, exc)
22
23
24 @app.get("/items/{item_id}")
25 async def read_item(item_id: int):
26 if item_id == 3:
27 raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
28 return {"item_id": item_id}