from fastapi import HTTPException, status
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):
      if(str(e) == ''):
          content += e.detail
          self.detail = e.detail
          self.status_code = e.status_code
      else:
          self.detail = str(e)
          content += str(e)
          self.status_code = 500
      if(len(content) > 5000):
         content =content[0:5000]
      self.error = ErrorCreate(location=location,title=title,content=content)

def writedblog(exc: APIException):
    db = SessionLocal()
    try:
        create_log(db,exc.error)
    finally:
        db.close()