From e59082fa7fa2fbced1bae204010de09e506c6a34 Mon Sep 17 00:00:00 2001 From: Alexander Berger Date: Tue, 5 Nov 2024 10:28:35 -0500 Subject: [PATCH] Adding controller utilities module --- src/geneweaver/api/controller/utilities.py | 36 ++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/geneweaver/api/controller/utilities.py diff --git a/src/geneweaver/api/controller/utilities.py b/src/geneweaver/api/controller/utilities.py new file mode 100644 index 0000000..2481026 --- /dev/null +++ b/src/geneweaver/api/controller/utilities.py @@ -0,0 +1,36 @@ +"""Utilities for FastAPI Controller.""" + +from fastapi import HTTPException + +from . import message as api_message + +EXCEPTION_MAP = { + api_message.ACCESS_FORBIDDEN: HTTPException( + status_code=403, detail=api_message.ACCESS_FORBIDDEN + ), + api_message.INACCESSIBLE_OR_FORBIDDEN: HTTPException( + status_code=404, detail=api_message.INACCESSIBLE_OR_FORBIDDEN + ), + api_message.RECORD_NOT_FOUND_ERROR: HTTPException( + status_code=404, detail=api_message.RECORD_NOT_FOUND_ERROR + ), + api_message.RECORD_EXISTS: HTTPException( + status_code=412, detail=api_message.RECORD_EXISTS + ), +} + + +def raise_http_error(response: dict) -> None: + """Raise HTTPException based on response message. + + :param response: dict + + raises: HTTPException if "error" key is in response dict. + """ + if "error" in response: + try: + raise EXCEPTION_MAP[response.get("message")] + except KeyError: + raise HTTPException( + status_code=500, detail=api_message.UNEXPECTED_ERROR + ) from None