0
0
FastAPIframework~5 mins

Global exception middleware in FastAPI

Choose your learning style9 modes available
Introduction

Global exception middleware helps catch errors in one place. It stops your app from crashing and shows friendly error messages.

You want to handle all errors in your FastAPI app consistently.
You want to log errors for debugging without repeating code.
You want to send custom error responses to users.
You want to catch unexpected errors and avoid server crashes.
Syntax
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.

Examples
This example catches all exceptions and returns a simple error message.
FastAPI
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."})
This example logs the error to the console before sending a response.
FastAPI
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"})
Sample Program

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.

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)}
        )

@app.get("/divide")
async def divide(a: int, b: int):
    result = a / b  # This can raise ZeroDivisionError
    return {"result": result}
OutputSuccess
Important Notes

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.

Summary

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.