"""Exceptions and their handlers for the platform backend."""importjsonimportloggingfromhttpimportHTTPStatusfromtypingimportAnyfromconnexion.lifecycleimportConnexionRequest,ConnexionResponselogger=logging.getLogger(__name__)
[docs]classAPIException(Exception):"""Base exception for all API errors."""status_code=HTTPStatus.INTERNAL_SERVER_ERROR.valueerror_code="internal_error"def__init__(self,message=None,details=None):"""Initialize the exception with an optional message and details."""self.message=messageorself.__doc__self.details=detailssuper().__init__(self.message)
[docs]defto_dict(self)->dict[str,Any]:"""Convert exception to a dict representation."""result={"error":self.error_code,"message":self.message}ifself.details:result["details"]=self.detailsreturnresult
[docs]defhandle_api_exception(request:ConnexionRequest,exc:Exception)->ConnexionResponse:"""Handler for our custom APIException hierarchy."""# Cast to APIException since we know this handler is only called for APIExceptionexc=excifisinstance(exc,APIException)elseAPIException(str(exc))ifexc.status_code>=HTTPStatus.INTERNAL_SERVER_ERROR.value:logger.error(f"Server error: {exc.message}",exc_info=True)else:logger.warning(f"Client error: {exc.message}")returnConnexionResponse(status_code=exc.status_code,body=json.dumps(exc.to_dict()),mimetype="application/json",)