Global exception middleware helps catch errors in one place. It stops your app from crashing and shows friendly error messages.
Global exception middleware in FastAPI
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.middleware("http") async def global_exception_middleware(request: Request, call_next): try: response = await call_next(request) return response except Exception as e: return JSONResponse( status_code=500, content={"detail": "An error occurred.", "error": str(e)} )
The middleware function must be async and accept request and call_next.
Use call_next(request) to continue processing the request.
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.middleware("http") async def catch_all_exceptions(request: Request, call_next): try: response = await call_next(request) return response except Exception: return JSONResponse(status_code=500, content={"message": "Oops! Something went wrong."})
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.middleware("http") async def log_and_handle_errors(request: Request, call_next): try: response = await call_next(request) return response except Exception as e: print(f"Error: {e}") # Log error return JSONResponse(status_code=500, content={"error": "Internal server error"})
This FastAPI app has a global exception middleware that catches all errors. The /divide endpoint divides two numbers. If you divide by zero, the middleware catches the error and returns a friendly JSON message instead of crashing.
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.middleware("http") async def global_exception_middleware(request: Request, call_next): try: response = await call_next(request) return response except Exception as e: return JSONResponse( status_code=500, content={"detail": "An error occurred.", "error": str(e)} ) @app.get("/divide") async def divide(a: int, b: int): result = a / b # This can raise ZeroDivisionError return {"result": result}
Global exception middleware catches errors from all routes in one place.
It helps keep your code clean by avoiding repeated try-except blocks.
Always return a proper HTTP response to avoid hanging requests.
Global exception middleware catches and handles errors for the whole FastAPI app.
It improves user experience by sending clear error messages.
It helps developers log and debug errors easily.