from fastapi import HTTPException, status import httpx from app.db.schemas import ErrorCreate from app.db.session import SessionLocal from app.db.crud import create_log class APIException(Exception): def __init__(self, location: str, title: str, content: str, e: Exception): self.detail = str(e) self.status_code = 500 if isinstance(e,httpx.HTTPStatusError): try: error_response = e.response.json() self.detail = error_response.get('message', self.detail) self.status_code = e.response.status_code content += self.detail except ValueError: pass elif hasattr(e, 'detail'): self.detail = e.detail self.status_code = e.status_code if hasattr(e, 'status_code') else 500 content += e.detail else: self.detail = str(e) self.status_code = 500 content += str(e) if len(content) > 5000: content = content[:5000] self.error = ErrorCreate(location=location, title=title, content=content) super().__init__(self.error) def writedblog(exc: APIException): db = SessionLocal() try: create_log(db,exc.error) finally: db.close()