Performance: Custom exception handlers
This affects server response time and user experience by controlling how errors are processed and returned.
Jump into concepts and practice - no test required
from fastapi import FastAPI from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(Exception) async def generic_exception_handler(request, exc): # Minimal processing, quick response return JSONResponse(status_code=500, content={"detail": "Internal Server Error"})
from fastapi import FastAPI from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(Exception) async def generic_exception_handler(request, exc): # Heavy logging and complex processing here import time import asyncio await asyncio.sleep(2) # Simulate slow processing asynchronously return JSONResponse(status_code=500, content={"detail": "Internal Server Error"})
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy blocking exception handler | N/A | N/A | N/A | [X] Bad |
| Lightweight async exception handler | N/A | N/A | N/A | [OK] Good |
add_exception_handler to register handlers.MyException is raised?
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
app = FastAPI()
class MyException(Exception):
pass
@app.exception_handler(MyException)
async def my_exception_handler(request: Request, exc: MyException):
return JSONResponse(status_code=418, content={"message": "Custom error occurred"})
@app.get("/test")
async def test():
raise MyException()status_code=418.MyException triggers the handler, which sends the 418 status.from fastapi import FastAPI
app = FastAPI()
class CustomError(Exception):
pass
@app.exception_handler(CustomError)
def handler(exc: CustomError):
return {"error": "Something went wrong"}ValueError is raised. Which code snippet correctly implements this?