In FastAPI, what is the main reason to use error handling like HTTPException?
Think about how users get feedback when something fails.
Error handling in FastAPI helps send clear messages to users when something goes wrong. This improves reliability by avoiding crashes and giving understandable responses.
Consider a FastAPI endpoint that raises a ValueError but does not catch it. What will the client receive?
from fastapi import FastAPI app = FastAPI() @app.get("/error") def error_endpoint(): raise ValueError("Oops")
Think about default behavior when exceptions are not caught.
When an error is not handled, FastAPI returns a 500 status code with a generic message. This prevents the server from crashing but does not give detailed info to the client.
Given this FastAPI code, what will the client see when accessing /custom-error?
from fastapi import FastAPI, Request, HTTPException from fastapi.responses import JSONResponse app = FastAPI() class MyError(Exception): pass @app.exception_handler(MyError) async def my_error_handler(request: Request, exc: MyError): return JSONResponse(status_code=418, content={"message": "Custom error occurred"}) @app.get("/custom-error") async def custom_error(): raise MyError()
Look at the custom exception handler and its response.
The custom handler catches MyError and returns a JSON response with status 418 and a custom message, so the client sees that message and status.
Which option is syntactically correct for defining a FastAPI exception handler?
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(ValueError) async def value_error_handler(request: Request, exc: ValueError): return JSONResponse(status_code=400, content={"error": str(exc)})
Check for missing colons, commas, and indentation.
Option B is correct syntax. Option B misses colons in parameters. Option B lacks indentation. Option B misses a comma between arguments.
Given this code, why does the custom error handler not respond when /fail is called?
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() class CustomError(Exception): pass @app.get("/fail") async def fail(): raise CustomError("fail") @app.exception_handler(ValueError) async def value_error_handler(request: Request, exc: ValueError): return JSONResponse(status_code=400, content={"error": "Value error caught"})
Check the exception types in the handler and the raised error.
The handler only catches ValueError exceptions. Since CustomError is raised, it is not caught by that handler and results in a default 500 error.