Spaces:
Running on Zero
Running on Zero
File size: 3,149 Bytes
bf90f9f c19e0b6 bf90f9f c19e0b6 bf90f9f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | import uuid
from typing import Any, Optional
from fastapi import Request, status
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from app.logging_config import request_id_ctx
class AppError(Exception):
def __init__(
self,
code: str,
message: str,
status_code: int = status.HTTP_400_BAD_REQUEST,
retryable: bool = False,
details: Optional[dict[str, Any]] = None
):
self.code = code
self.message = message
self.status_code = status_code
self.retryable = retryable
self.details = details or {}
super().__init__(message)
def make_error_payload(code: str, message: str, retryable: bool, details: dict, request_id: str) -> dict:
return {
"error": {
"code": code,
"message": message,
"retryable": retryable,
"details": details,
"request_id": request_id
}
}
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
req_id = request_id_ctx.get() or f"req_{uuid.uuid4().hex[:8]}"
return JSONResponse(
status_code=exc.status_code,
content=make_error_payload(exc.code, exc.message, exc.retryable, exc.details, req_id),
headers={"X-Request-ID": req_id}
)
async def validation_error_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
req_id = request_id_ctx.get() or f"req_{uuid.uuid4().hex[:8]}"
errors = exc.errors()
details = {"errors": [{"loc": list(e.get("loc", [])), "msg": e.get("msg", ""), "type": e.get("type", "")} for e in errors]}
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content=make_error_payload("REQUEST_INVALID", "Request parameters or body failed validation.", False, details, req_id),
headers={"X-Request-ID": req_id}
)
async def http_error_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse:
req_id = request_id_ctx.get() or f"req_{uuid.uuid4().hex[:8]}"
code_map = {
404: "NOT_FOUND",
401: "UNAUTHORIZED",
403: "FORBIDDEN",
405: "METHOD_NOT_ALLOWED",
413: "FILE_TOO_LARGE",
415: "INVALID_FILE_TYPE",
429: "TOO_MANY_REQUESTS",
503: "SERVICE_UNAVAILABLE"
}
code = code_map.get(exc.status_code, "HTTP_ERROR")
headers = {"X-Request-ID": req_id}
if exc.headers:
headers.update(exc.headers)
return JSONResponse(
status_code=exc.status_code,
content=make_error_payload(code, str(exc.detail), False, {}, req_id),
headers=headers
)
async def generic_error_handler(request: Request, exc: Exception) -> JSONResponse:
req_id = request_id_ctx.get() or f"req_{uuid.uuid4().hex[:8]}"
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content=make_error_payload("INTERNAL_ERROR", "An unexpected internal server error occurred.", False, {}, req_id),
headers={"X-Request-ID": req_id}
)
|