finish api exception handling
This commit is contained in:
1 parent
1665d11d66
commit
e30e7304df
6 files changed
+828
-192
No files matched your search
+86
-26
@@ -59,8 +59,28 @@ from typing import Any, List, Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from config import apikey_settings
|
||||
from app.song.schemas.song_schema import PollingSongResponse, SongClipData
|
||||
from app.utils.logger import get_logger
|
||||
from config import apikey_settings, recovery_settings
|
||||
|
||||
logger = get_logger("suno")
|
||||
|
||||
|
||||
class SunoResponseError(Exception):
|
||||
"""Suno API 응답 오류 시 발생하는 예외
|
||||
|
||||
Suno API 거부 응답 또는 비정상 응답 시 사용됩니다.
|
||||
재시도 로직에서 이 예외를 catch하여 재시도를 수행합니다.
|
||||
|
||||
Attributes:
|
||||
message: 에러 메시지
|
||||
original_response: 원본 API 응답 (있는 경우)
|
||||
"""
|
||||
|
||||
def __init__(self, message: str, original_response: dict | None = None):
|
||||
self.message = message
|
||||
self.original_response = original_response
|
||||
super().__init__(self.message)
|
||||
|
||||
|
||||
class SunoService:
|
||||
@@ -122,34 +142,74 @@ class SunoService:
|
||||
if genre:
|
||||
payload["style"] = genre
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
f"{self.BASE_URL}/generate",
|
||||
headers=self.headers,
|
||||
json=payload,
|
||||
timeout=30.0,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
last_error: Exception | None = None
|
||||
|
||||
# 응답: {"code": 200, "msg": "success", "data": {"taskId": "..."}}
|
||||
# API 응답 검증
|
||||
if data is None:
|
||||
raise ValueError("Suno API returned empty response")
|
||||
for attempt in range(recovery_settings.SUNO_MAX_RETRIES + 1):
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
f"{self.BASE_URL}/generate",
|
||||
headers=self.headers,
|
||||
json=payload,
|
||||
timeout=recovery_settings.SUNO_DEFAULT_TIMEOUT,
|
||||
)
|
||||
|
||||
if data.get("code") != 200:
|
||||
error_msg = data.get("msg", "Unknown error")
|
||||
raise ValueError(f"Suno API error: {error_msg}")
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
|
||||
response_data = data.get("data")
|
||||
if response_data is None:
|
||||
raise ValueError(f"Suno API response missing 'data' field: {data}")
|
||||
# API 응답 검증
|
||||
if data is None:
|
||||
raise SunoResponseError("Suno API returned empty response")
|
||||
|
||||
task_id = response_data.get("taskId")
|
||||
if task_id is None:
|
||||
raise ValueError(f"Suno API response missing 'taskId': {response_data}")
|
||||
if data.get("code") != 200:
|
||||
error_msg = data.get("msg", "Unknown error")
|
||||
raise SunoResponseError(f"Suno API error: {error_msg}", original_response=data)
|
||||
|
||||
return task_id
|
||||
response_data = data.get("data")
|
||||
if response_data is None:
|
||||
raise SunoResponseError(f"Suno API response missing 'data' field", original_response=data)
|
||||
|
||||
task_id = response_data.get("taskId")
|
||||
if task_id is None:
|
||||
raise SunoResponseError(f"Suno API response missing 'taskId'", original_response=response_data)
|
||||
|
||||
return task_id
|
||||
|
||||
# 재시도 불가능한 오류 (4xx 클라이언트 오류)
|
||||
if 400 <= response.status_code < 500:
|
||||
raise SunoResponseError(
|
||||
f"Client error: {response.status_code}",
|
||||
original_response={"status": response.status_code, "text": response.text},
|
||||
)
|
||||
|
||||
# 재시도 가능한 오류 (5xx 서버 오류)
|
||||
last_error = SunoResponseError(
|
||||
f"Server error: {response.status_code}",
|
||||
original_response={"status": response.status_code, "text": response.text},
|
||||
)
|
||||
|
||||
except httpx.TimeoutException as e:
|
||||
logger.warning(
|
||||
f"[Suno] Timeout on attempt {attempt + 1}/{recovery_settings.SUNO_MAX_RETRIES + 1}"
|
||||
)
|
||||
last_error = e
|
||||
|
||||
except httpx.HTTPError as e:
|
||||
logger.warning(f"[Suno] HTTP error on attempt {attempt + 1}: {e}")
|
||||
last_error = e
|
||||
|
||||
except SunoResponseError:
|
||||
raise # SunoResponseError는 재시도하지 않고 즉시 전파
|
||||
|
||||
# 마지막 시도가 아니면 재시도
|
||||
if attempt < recovery_settings.SUNO_MAX_RETRIES:
|
||||
logger.info(f"[Suno] Retrying... ({attempt + 1}/{recovery_settings.SUNO_MAX_RETRIES})")
|
||||
|
||||
# 모든 재시도 실패
|
||||
raise SunoResponseError(
|
||||
f"All {recovery_settings.SUNO_MAX_RETRIES + 1} attempts failed",
|
||||
original_response={"last_error": str(last_error)},
|
||||
)
|
||||
|
||||
async def get_task_status(self, task_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
@@ -170,7 +230,7 @@ class SunoService:
|
||||
f"{self.BASE_URL}/generate/record-info",
|
||||
headers=self.headers,
|
||||
params={"taskId": task_id},
|
||||
timeout=30.0,
|
||||
timeout=recovery_settings.SUNO_DEFAULT_TIMEOUT,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
@@ -198,7 +258,7 @@ class SunoService:
|
||||
f"{self.BASE_URL}/generate/get-timestamped-lyrics",
|
||||
headers=self.headers,
|
||||
json=payload,
|
||||
timeout=120.0,
|
||||
timeout=recovery_settings.SUNO_LYRIC_TIMEOUT,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
Reference in new issue
Block a user