Skip to content

Commit

Permalink
Refactor exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
reedsa committed Sep 12, 2023
1 parent 117b5cd commit 6532d14
Showing 1 changed file with 16 additions and 22 deletions.
38 changes: 16 additions & 22 deletions web3/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,15 @@
METHOD_NOT_FOUND = -32601


def _raise_bad_response_format(response: RPCResponse, error: str = "") -> None:
error_message = f"The error is: {error}. " if error else ""
raise BadResponseFormat(
"The response was in an unexpected format and unable to be parsed. "
f"{error_message}"
f"The raw response is: {response}"
)


def apply_error_formatters(
error_formatters: Callable[..., Any],
response: RPCResponse,
Expand Down Expand Up @@ -212,17 +221,11 @@ def formatted_response(
null_result_formatters: Optional[Callable[..., Any]] = None,
) -> Any:
if "jsonrpc" in response and response["jsonrpc"] != "2.0":
raise BadResponseFormat(
"The response was in an unexpected format and unable to be parsed. "
f'The error is: "jsonrpc" must equal "2.0". '
f"The raw response is: {response}"
)
_raise_bad_response_format(response, '"jsonrpc" must equal "2.0"')

if "id" in response and not isinstance(response["id"], (str, int, None)):
raise BadResponseFormat(
"The response was in an unexpected format and unable to be parsed. "
f'The error is: "id" must be a string, integer or null. '
f"The raw response is: {response}"
_raise_bad_response_format(
response, '"id" must be a string, integer or null'
)

# Format and validate errors
Expand All @@ -235,19 +238,13 @@ def formatted_response(
# https://docs.alchemy.com/reference/error-reference#json-rpc-error-codes
code = error.get("code")
if not isinstance(code, int):
raise BadResponseFormat(
"The response was in an unexpected format and unable to be parsed. "
f"The error is: error['code'] must be an integer. "
f"The raw response is: {response}"
)
_raise_bad_response_format(response, "error['code'] must be an integer")
elif code == METHOD_NOT_FOUND:
raise MethodUnavailable(error)

if not type(error.get("message")) in (str, int, None):
raise BadResponseFormat(
"The response was in an unexpected format and unable to be parsed. "
f"The error is: error['message'] must be a string, integer "
f"or null. The raw response is: {response}"
_raise_bad_response_format(
response, "error['message'] must be a string, integer or null"
)

apply_error_formatters(error_formatters, response)
Expand All @@ -270,10 +267,7 @@ def formatted_response(
return response["params"]["result"]

else:
raise BadResponseFormat(
"The response was in an unexpected format and unable to be parsed. "
f"The raw response is: {response}"
)
_raise_bad_response_format(response)

def request_blocking(
self,
Expand Down

0 comments on commit 6532d14

Please sign in to comment.