Complete the code to import the correct FastAPI class.
from fastapi import [1] app = [1]()
The FastAPI class is imported to create the app instance.
Complete the code to define a custom exception handler for HTTPException.
@app.exception_handler([1]) async def http_exception_handler(request, exc): return JSONResponse(status_code=exc.status_code, content={"message": exc.detail})
The HTTPException class is used to catch HTTP errors in FastAPI.
Fix the error in the custom exception handler to return a JSON response.
from fastapi.responses import [1] @app.exception_handler(ValueError) async def value_error_handler(request, exc): return [1](status_code=400, content={"error": str(exc)})
Use JSONResponse to send JSON content back to the client.
Fill both blanks to create a custom exception and handler that returns a JSON error message.
class CustomError(Exception): def __init__(self, message): self.message = message @app.exception_handler([1]) async def custom_error_handler(request, exc): return JSONResponse(status_code=[2], content={"error": exc.message})
The handler catches CustomError and returns status code 400.
Fill all three blanks to raise a custom exception and handle it with a JSON response.
class MyException(Exception): def __init__(self, detail): self.detail = detail @app.get("/error") async def error_route(): raise [1]("Something went wrong") @app.exception_handler([2]) async def my_exception_handler(request, exc): return JSONResponse(status_code=[3], content={"error": exc.detail})
The route raises MyException, which is handled by the custom handler returning status 400.
