Get startedGet started for free

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.

This exercise is part of the course

Deploying AI into Production with FastAPI

View Course

Exercise instructions

  • 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.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# 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)
Edit and Run Code