Which of the following code snippets correctly implements this behavior?
hard🚀 Application Q15 of 15
FastAPI - Error Handling
You want to create a FastAPI app that returns a custom error response with fields error_code (int) and error_msg (str) whenever a RuntimeError occurs. Which of the following code snippets correctly implements this behavior?
class CustomError(BaseModel): error_code: int; error_msg: str
@app.exception_handler(RuntimeError)
async def runtime_error_handler(request: Request, exc: RuntimeError):
return JSONResponse(status_code=500, content=CustomError(error_code=1001, error_msg=str(exc)).dict()) defines CustomError inheriting from BaseModel with correct field types (int and str).
Step 2: Implement exception handler properly
class CustomError(BaseModel): error_code: int; error_msg: str
@app.exception_handler(RuntimeError)
async def runtime_error_handler(request: Request, exc: RuntimeError):
return JSONResponse(status_code=500, content=CustomError(error_code=1001, error_msg=str(exc)).dict())'s handler returns JSONResponse with status 500 and content as dict from CustomError instance, converting exception to string.
Step 3: Check other options for errors
class CustomError(BaseModel): error_code: str; error_msg: int
@app.exception_handler(RuntimeError)
async def runtime_error_handler(request: Request, exc: RuntimeError):
return JSONResponse(status_code=400, content=CustomError(error_code='1001', error_msg=exc).dict()) swaps types incorrectly and passes exc without str(); class CustomError:
def __init__(self, error_code, error_msg):
self.error_code = error_code
self.error_msg = error_msg
@app.exception_handler(RuntimeError)
async def runtime_error_handler(request: Request, exc: RuntimeError):
return JSONResponse(status_code=500, content=CustomError(1001, str(exc))) uses plain class not BaseModel and returns object not dict; @app.exception_handler(RuntimeError)
async def runtime_error_handler(request: Request, exc: RuntimeError):
return JSONResponse(status_code=500, content={'error_code': 1001, 'error_msg': str(exc)}) skips model usage.
Final Answer:
Option A correctly defines model and handler returning proper JSON response -> Option A
Quick Check:
Use BaseModel with typed fields and dict() in handler [OK]
Quick Trick:Use BaseModel and dict() for error response content [OK]
Common Mistakes:
MISTAKES
Swapping field types in model
Not converting exception to string
Returning model instance instead of dict
Skipping Pydantic model for error response
Master "Error Handling" in FastAPI
9 interactive learning modes - each teaches the same concept differently