Performance: Custom error response models
This affects the server response time and payload size, impacting how quickly error information is delivered and rendered in the client.
from fastapi import FastAPI from fastapi.responses import JSONResponse from pydantic import BaseModel app = FastAPI() class ErrorResponse(BaseModel): error_code: int message: str @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id == 0: return JSONResponse(status_code=404, content=ErrorResponse(error_code=404, message="Item not found").dict()) return {"item_id": item_id}
from fastapi import FastAPI, HTTPException app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id == 0: raise HTTPException(status_code=404, detail="Item not found") return {"item_id": item_id}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Default HTTPException with string detail | N/A (API response only) | N/A | Minimal paint cost on client | [!] OK |
| Custom error response model with Pydantic | N/A (API response only) | N/A | Slightly higher paint cost due to larger payload | [OK] Good |
ValueError is raised?
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
app = FastAPI()
class ErrorResponse(BaseModel):
detail: str
@app.exception_handler(ValueError)
async def value_error_handler(request: Request, exc: ValueError):
return JSONResponse(
status_code=400,
content=ErrorResponse(detail=str(exc)).dict()
)
@app.get("/test")
async def test():
raise ValueError("Invalid input")from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
app = FastAPI()
class ErrorResponse(BaseModel):
message: str
@app.exception_handler(KeyError)
async def key_error_handler(request: Request, exc: KeyError):
return JSONResponse(
status_code=404,
content=ErrorResponse(message=exc).dict()
)error_code (int) and error_msg (str) whenever a RuntimeError occurs. Which of the following code snippets correctly implements this behavior?Pass the test and this pattern moves unknown