60 lines
2.9 KiB
Python
60 lines
2.9 KiB
Python
"""
|
|
HealthSync AI 기본 컨트롤러 클래스
|
|
"""
|
|
from fastapi import HTTPException, status
|
|
from typing import Any
|
|
|
|
from fastapi.params import Depends
|
|
|
|
from app.core.dependencies import get_settings
|
|
from app.models.base import BaseResponse, ErrorResponse
|
|
from app.config.settings import settings, Settings
|
|
import logging
|
|
from datetime import datetime
|
|
|
|
class BaseController:
|
|
"""기본 컨트롤러 클래스"""
|
|
|
|
def __init__(self):
|
|
self.settings = settings
|
|
self.logger = logging.getLogger(self.__class__.__name__)
|
|
|
|
def create_success_response(self, data: Any = None, message: str = "성공적으로 처리되었습니다.") -> BaseResponse:
|
|
"""성공 응답 생성"""
|
|
return BaseResponse(success=True, message=message, data=data, timestamp=datetime.now())
|
|
|
|
def handle_service_error(self, error: Exception, operation: str = "unknown"):
|
|
"""서비스 에러 처리"""
|
|
self.logger.error(f"Service error in {operation}: {str(error)}", exc_info=True)
|
|
|
|
if isinstance(error, ValueError):
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(error))
|
|
else:
|
|
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="서버 내부 오류가 발생했습니다.")
|
|
|
|
def log_request(self, endpoint: str, user_id: int = None, **kwargs):
|
|
"""요청 로그 기록"""
|
|
log_data = {"endpoint": endpoint, "controller": self.__class__.__name__, "timestamp": datetime.now().isoformat()}
|
|
if user_id:
|
|
log_data["user_id"] = user_id
|
|
log_data.update(kwargs)
|
|
self.logger.info(f"Request to {endpoint}", extra=log_data)
|
|
|
|
def handle_service_error(self, error: Exception, operation: str = "unknown"):
|
|
"""서비스 에러 처리"""
|
|
self.logger.error(f"Service error in {operation}: {str(error)}", exc_info=True)
|
|
|
|
if isinstance(error, ValueError):
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(error))
|
|
elif "찾을 수 없습니다" in str(error) or "없음" in str(error):
|
|
# 데이터 조회 실패인 경우 404로 처리
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(error))
|
|
elif "Claude API" in str(error) or "AI" in str(error):
|
|
# AI 서비스 오류인 경우 구체적 메시지 전달
|
|
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=f"AI 서비스 오류: {str(error)}")
|
|
elif "데이터베이스" in str(error) or "쿼리" in str(error):
|
|
# 데이터베이스 오류인 경우
|
|
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=f"데이터베이스 오류: {str(error)}")
|
|
else:
|
|
# 기타 오류는 구체적 메시지와 함께 500으로 처리
|
|
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(error)) |