Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Deploying AI into Production with FastAPI

Cursus bekijken

Oefeninstructies

  • Import the class for plain text responses.
  • Annotate validation_exception_handler as a global exception handler.
  • Return a plain text response for any validation exception.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# 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)
Code bewerken en uitvoeren