Skip to content

Commit 59b5815

Browse files
committed
refactor: improve error handling and message
1 parent a314ef0 commit 59b5815

File tree

3 files changed

+24
-3
lines changed

3 files changed

+24
-3
lines changed

backend/app/api/v1/chat.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from app.config import settings
55
from app.database import get_db
6+
from app.exceptions import CreditLimitExceededException
67
from app.logger import Logger
78
from app.models.asset_content import AssetProcessingStatus
89
from app.repositories import (
@@ -256,11 +257,17 @@ def draft_with_ai(draft_request: DraftRequest, db: Session = Depends(get_db)):
256257
if not api_key:
257258
raise HTTPException(status_code=404, detail="API Key not found!")
258259

259-
response = request_draft_with_ai(api_key.key, draft_request.model_dump_json())
260+
try:
261+
response = request_draft_with_ai(api_key.key, draft_request.model_dump_json())
262+
263+
except CreditLimitExceededException:
264+
raise HTTPException(
265+
status_code=402, detail="Credit limit Reached, Wait next month or upgrade your Plan!"
266+
)
260267

261268
return {
262269
"status": "success",
263-
"message": "Draft sucessfully generated!",
270+
"message": "Draft successfully generated!",
264271
"data": {"response": response["response"]},
265272
}
266273

backend/app/requests/__init__.py

+6
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,12 @@ def request_draft_with_ai(api_token: str, draft_request: dict) -> dict:
235235

236236
try:
237237
if response.status_code not in [200, 201]:
238+
239+
if response.status_code == 402:
240+
raise CreditLimitExceededException(
241+
response.json().get("detail", "Credit limit exceeded!")
242+
)
243+
238244
logger.error(
239245
f"Failed to draft with AI. It returned {response.status_code} code: {response.text}"
240246
)

frontend/src/services/chat.tsx

+9-1
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,14 @@ export const draft_with_ai = async (data: ChatDraftRequest) => {
6363
);
6464
return response.data.data;
6565
} catch (error) {
66-
throw error;
66+
if (axios.isAxiosError(error)) {
67+
if (error.response?.data) {
68+
throw new Error(error.response.data.detail);
69+
} else {
70+
throw new Error("Failed to generate draft with AI. Please try again.");
71+
}
72+
} else {
73+
throw new Error("Failed to generate draft with AI. Please try again.");
74+
}
6775
}
6876
};

0 commit comments

Comments
 (0)