58 lines
1.4 KiB
Python
58 lines
1.4 KiB
Python
from fastapi import HTTPException, Request, status
|
|
from fastapi.responses import JSONResponse
|
|
from pydantic import ValidationError
|
|
|
|
|
|
class APIError(HTTPException):
|
|
def __init__(
|
|
self,
|
|
status_code: int,
|
|
detail: str,
|
|
error_code: str = None,
|
|
):
|
|
super().__init__(status_code=status_code, detail=detail)
|
|
self.error_code = error_code
|
|
|
|
|
|
async def http_error_handler(request: Request, exc: HTTPException) -> JSONResponse:
|
|
"""
|
|
Handle HTTP exceptions.
|
|
"""
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content={"detail": exc.detail}
|
|
)
|
|
|
|
|
|
async def api_error_handler(request: Request, exc: APIError) -> JSONResponse:
|
|
"""
|
|
Handle custom API exceptions.
|
|
"""
|
|
headers = getattr(exc, "headers", None)
|
|
|
|
if exc.error_code:
|
|
content = {"detail": exc.detail, "code": exc.error_code}
|
|
else:
|
|
content = {"detail": exc.detail}
|
|
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content=content,
|
|
headers=headers,
|
|
)
|
|
|
|
|
|
async def validation_error_handler(
|
|
request: Request,
|
|
exc: ValidationError
|
|
) -> JSONResponse:
|
|
"""
|
|
Handle validation errors.
|
|
"""
|
|
return JSONResponse(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
content={
|
|
"detail": exc.errors(),
|
|
"body": exc.body,
|
|
},
|
|
) |