Global exception handler
Your API to update inventory has been getting more use, and some users have started to complain that validation errors encoded in JSON are hard to read. Let's create a global error handler to return request validation errors as plain text.
The RequestValidationError exception has been pre-loaded for you.
Latihan ini adalah bagian dari kursus
Deploying AI into Production with FastAPI
Petunjuk latihan
- Import the class for plain text responses.
- Annotate
validation_exception_handleras a global exception handler. - Return a plain text response for any validation exception.
Latihan interaktif praktis
Cobalah latihan ini dengan menyelesaikan kode contoh berikut.
# Import class for plain text response
from fastapi.responses import ____
app = FastAPI()
# Create global exception handler
@app.____(RequestValidationError)
async def validation_exception_handler(request, exc):
# Return plain text response
return ____(str(exc), status_code=400)