-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added new exception types, added utility classes, added some test cas…
…es for userApi
- Loading branch information
1 parent
b4ef150
commit 54a8ec1
Showing
13 changed files
with
357 additions
and
35 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
from .server_exception import ServerException | ||
from .standard_exception import StandardException |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
from typing import Any, Dict, List, Optional | ||
|
||
|
||
class ServerException(Exception): | ||
""" | ||
Custom exception class for server-related errors. | ||
""" | ||
|
||
def __init__( | ||
self, | ||
http_status_code: int, | ||
message: str, | ||
request_data: Optional[Dict[str, Any]] = None, | ||
runtime: Optional[float] = None, | ||
error: Optional[Dict[str, Any]] = None, | ||
) -> None: | ||
"""Initialize ServerException with specific attributes. | ||
Args: | ||
http_status_code (int): HTTP status code associated with the error | ||
message (str): Error message | ||
request_data (Optional[Dict[str, Any]], optional): Additional data associated with the request (optional) | ||
runtime (Optional[float], optional): Runtime information (optional). Defaults to None. | ||
error (Optional[Dict[str, Any]], optional): Specific error information (optional). Defaults to None. | ||
""" | ||
self.http_status_code: int = http_status_code | ||
self.request_data: Dict[str, Any] = request_data or {} | ||
self.runtime: float | None = runtime | ||
self.error: Dict[str, Any] = error or {} | ||
|
||
validation_messages: List[str] = self.get_validation_messages() | ||
message += f' (HTTP status code: {http_status_code}, validation messages: {"; ".join(validation_messages)})' | ||
|
||
super().__init__(message) | ||
|
||
def get_validation_messages(self) -> List[str]: | ||
"""Get the validation messages from the error information. | ||
Returns: | ||
List[str]: List of validation messages | ||
""" | ||
validation: List[Dict[str, Any]] = self.error.get("validation", []) | ||
return [f"{item['field']}: {item['message']}" for item in validation] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
class StandardException(Exception): | ||
""" | ||
Custom exception class for standard exceptions. | ||
""" | ||
|
||
pass |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from .util import Util |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,163 @@ | ||
import json | ||
from typing import Any, Dict | ||
|
||
from corbado_python_sdk.exceptions import ServerException, StandardException | ||
from corbado_python_sdk.generated import ApiException, GenericRsp, RequestData | ||
|
||
|
||
class Util: | ||
""" | ||
Helper class containing various utility methods. | ||
""" | ||
|
||
@staticmethod | ||
def json_encode(data: Any) -> str: | ||
"""JSON encode. | ||
Args: | ||
data (Any): Data to be encoded. | ||
Raises: | ||
StandardException: If encoding fails. | ||
Returns: | ||
str: Encoded JSON string. | ||
""" | ||
try: | ||
json_str: str = json.dumps(data) | ||
except json.JSONDecodeError as e: | ||
raise StandardException(f"json.dumps() failed: {e}") | ||
return json_str | ||
|
||
@staticmethod | ||
def json_decode(data: str) -> Dict[str, Any]: | ||
""" | ||
JSON decode. | ||
Args: | ||
data (str): Data to be decoded. | ||
Raises: | ||
StandardException: If decoding fails. | ||
Returns: | ||
Dict[str, Any]: Decoded data as a dictionary. | ||
""" | ||
try: | ||
decoded_data = json.loads(data) | ||
except json.JSONDecodeError as e: | ||
raise StandardException(f"json.loads() failed: {e}") | ||
return decoded_data | ||
|
||
@staticmethod | ||
def is_error_http_status_code(status_code: int) -> bool: | ||
""" | ||
Check if the status code indicates an error. | ||
Args: | ||
status_code (int): Status code. | ||
Returns: | ||
bool: True if status code indicates an error, False otherwise. | ||
""" | ||
return status_code >= 300 | ||
|
||
@staticmethod | ||
def throw_server_exception_old(data: Dict[str, Any]) -> None: | ||
""" | ||
Throw a ServerException based on the provided data. | ||
Args: | ||
data (Dict[str, Any]): Data. | ||
Raises: | ||
StandardException: If required keys are missing in the data. | ||
ServerException: Transformed server exception. | ||
""" | ||
# Check for error data, not existent for 404 for example | ||
data["error"] = data.get("error", {}) | ||
keys_to_check: list[str] = ["httpStatusCode", "message", "requestData", "runtime"] | ||
for key in keys_to_check: | ||
if key not in data: | ||
raise StandardException(f"Key '{key}' not found in data") | ||
raise ServerException( | ||
http_status_code=data["httpStatusCode"], | ||
message=data["message"], | ||
request_data=data["requestData"], | ||
runtime=data["runtime"], | ||
error=data["error"], | ||
) | ||
|
||
@staticmethod | ||
def convert_to_server_exception(e: ApiException) -> ServerException: | ||
# TODO: move to server exception constructor | ||
""" | ||
Convert ApiException to ServerException. | ||
Args: | ||
e (ApiException): Exception to be converted. | ||
Raises: | ||
StandardException: If response body is not a string. | ||
Returns: | ||
ServerException: ServerException instance. | ||
""" | ||
print(e) | ||
body = e.body | ||
if not isinstance(body, str): | ||
raise StandardException("Response body is not a string") | ||
data: Dict[str, Any] = Util.json_decode(body) | ||
return ServerException( | ||
http_status_code=data["httpStatusCode"], | ||
message=data["message"], | ||
request_data=data["requestData"], | ||
runtime=data["runtime"], | ||
error=data["error"], | ||
) | ||
|
||
@staticmethod | ||
def hydrate_request_data(data: Dict[str, Any]) -> RequestData: | ||
""" | ||
Hydrate RequestData object from dictionary. | ||
Args: | ||
data (Dict[str, Any]): Data. | ||
Raises: | ||
StandardException: If required keys are missing in the data. | ||
Returns: | ||
RequestData: RequestData object. | ||
""" | ||
keys_to_check: list[str] = ["requestID", "link"] | ||
for key in keys_to_check: | ||
if key not in data: | ||
raise StandardException(f"Key '{key}' not found in data") | ||
return RequestData(requestID=data["requestID"], link=data["link"]) | ||
|
||
@staticmethod | ||
def hydrate_response(data: Dict[str, Any]) -> GenericRsp: | ||
""" | ||
Hydrate GenericRsp object from dictionary. | ||
Args: | ||
data (Dict[str, Any]): Data. | ||
Raises: | ||
StandardException: If required keys are missing in the data. | ||
Returns: | ||
GenericRsp: GenericRsp object. | ||
""" | ||
keys_to_check: list[str] = ["httpStatusCode", "message", "requestData", "runtime"] | ||
for key in keys_to_check: | ||
if key not in data: | ||
raise StandardException(f"Key '{key}' not found in data") | ||
request_data: RequestData = Util.hydrate_request_data(data["requestData"]) | ||
return GenericRsp( | ||
httpStatusCode=data["httpStatusCode"], | ||
message=data["message"], | ||
requestData=request_data, | ||
runtime=data["runtime"], | ||
) |
File renamed without changes.
Oops, something went wrong.