File size: 668 Bytes
ef865f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from fastapi import Request
from fastapi.responses import JSONResponse


class AppError(Exception):
    """Raise this anywhere in route/service code for a clean, consistent error response."""
    def __init__(self, message: str, code: str = "ERROR", status: int = 400, detail: dict = None):
        self.message = message
        self.code = code
        self.status = status
        self.detail = detail or {}
        super().__init__(message)


async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
    return JSONResponse(
        status_code=exc.status,
        content={"error": exc.message, "code": exc.code, "detail": exc.detail},
    )