Skip to content

11 Error Handling

DodaTech 1 min read

title: Error Handling in FastAPI REST APIs weight: 21 date: 2026-06-28 lastmod: 2026-06-28 description: Master error handling in FastAPI including HTTPException, custom exception handlers, validation error overrides, and consistent error response formatting. tags: [api-development, fastapi]


Error handling in FastAPI uses HTTPException for route errors, custom exception handlers for global formatting, and overrideable validation error handlers to return consistent error responses across all endpoints.

```python
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse

app = FastAPI()

class AppError(HTTPException):
    def __init__(self, code: str, message: str, status_code: int = 400):
        super().__init__(status_code=status_code, detail={
            "code": code,
            "message": message
        })

class NotFoundError(AppError):
    def __init__(self, resource: str, resource_id):
        super().__init__(
            code="NOT_FOUND",
            message=f"{resource} with id {resource_id} not found",
            status_code=404
        )

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    errors = [
        {"field": ".".join(str(x) for x in err["loc"]), "message": err["msg"]}
        for err in exc.errors()
    ]
    return JSONResponse(
        status_code=422,
        content={"status": "error", "error": {"code": "VALIDATION_ERROR", "details": errors}}
    )

@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    return JSONResponse(
        status_code=exc.status_code,
        content={"status": "error", "error": exc.detail}
    )

@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
    return JSONResponse(
        status_code=500,
        content={"status": "error", "error": {"code": "INTERNAL_ERROR", "message": "Something went wrong"}}
    )

Expected output for validation error:

{"status":"error","error":{"code":"VALIDATION_ERROR","details":[{"field":"body.name","message":"field required"}]}}

What's Next

Now learn about deep validation in Building REST APIs with FastAPI.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro