wag-managment-api-service-v.../api_objects/errors/errorHandlers.py

61 lines
2.5 KiB
Python

from typing import Any
# class HTTPExceptionInstance:
# def __init__(self, statuses, exceptions, exceptions_dict, errors_dict, response_model, error_language_dict):
# self.EXCEPTIONS = exceptions # from fastapi.exceptions import HTTPException
# self.STATUSES = statuses # from fastapi import status
# self.EXCEPTION_DICTS: dict = exceptions_dict
# self.ERRORS_DICT: dict = errors_dict
# self.ERRORS_LANG: dict = error_language_dict
# self.RESPONSE_MODEL: Any = response_model
class HTTPExceptionEvyos(Exception):
def __init__(self, error_code: str, lang: str):
self.error_code = error_code
self.lang = lang
class HTTPExceptionEvyosHandler:
def __init__(self, statuses, exceptions, exceptions_dict, errors_dict, response_model, error_language_dict):
self.EXCEPTIONS = exceptions # from fastapi.exceptions import HTTPException
self.STATUSES = statuses # from fastapi import status
self.EXCEPTION_DICTS: dict = exceptions_dict
self.ERRORS_DICT: dict = errors_dict
self.ERRORS_LANG: dict = error_language_dict
self.RESPONSE_MODEL: Any = response_model
def retrieve_error_status_code(self, exc: HTTPExceptionEvyos):
grab_status = self.ERRORS_DICT.get(str(exc.error_code).upper(), "")
grab_status_code = self.EXCEPTION_DICTS.get(str(grab_status).upper(), "500")
return getattr(self.STATUSES, str(grab_status_code), getattr(self.STATUSES, "HTTP_500_INTERNAL_SERVER_ERROR"))
def retrieve_error_message(self, exc: HTTPExceptionEvyos):
message_by_lang = self.ERRORS_LANG.get(str(exc.lang).lower(), {})
message_by_code = message_by_lang.get(str(exc.error_code).upper(), "Unknown error")
return message_by_code
def handle_exception(self, request, exc: HTTPExceptionEvyos):
headers = getattr(request, "headers", {})
status_code = self.retrieve_error_status_code(exc)
error_message = self.retrieve_error_message(exc)
return self.RESPONSE_MODEL(
status_code=int(status_code),
content={"message": error_message, "lang": exc.lang},
)
class HTTPExceptionAnyHandler:
def __init__(self, response_model):
self.RESPONSE_MODEL: Any = response_model
def any_exception_handler(self, request, exc: Exception):
return self.RESPONSE_MODEL(
status_code=200,
content={"message": str(exc), "lang": None, "status_code": 417},
)