Better error handling

This commit is contained in:
Eden Kirin
2023-04-23 10:03:50 +02:00
parent 6a64709d17
commit fb6d1276e6
2 changed files with 69 additions and 4 deletions

View File

@ -21,6 +21,10 @@ class PlayerNotFoundError(BaseError):
...
class ValidationError(BaseError):
...
class Direction(str, Enum):
LEFT = "left"
RIGHT = "right"
@ -105,7 +109,12 @@ class FairHopper:
"player_name": player_name,
}
r = requests.post(self.format_url("/game"), json=payload)
r.raise_for_status()
if r.status_code == 422:
raise ValidationError()
else:
r.raise_for_status()
return StartGameResponse(**r.json())
def get_game_info(self) -> GameInfoResponse:
@ -113,13 +122,15 @@ class FairHopper:
r.raise_for_status()
return GameInfoResponse(**r.json())
def get_player_info(self, id: str) -> PlayerInfoResponse:
r = requests.get(self.format_url(f"/player/{id}"))
def get_player_info(self, player_id: str) -> PlayerInfoResponse:
r = requests.get(self.format_url(f"/player/{player_id}"))
if r.status_code == 403:
raise PlayerInactiveError()
elif r.status_code == 404:
raise PlayerNotFoundError()
elif r.status_code == 422:
raise ValidationError()
else:
r.raise_for_status()
@ -147,6 +158,8 @@ class FairHopper:
raise PlayerNotFoundError()
elif r.status_code == 409:
raise PositionError()
elif r.status_code == 422:
raise ValidationError()
else:
r.raise_for_status()
@ -157,11 +170,32 @@ class FairHopper:
response_data = ProductListResponse(**r.json())
return response_data.products
def get_product(self, product_id: str) -> Product:
r = requests.get(self.format_url(f"/products/{product_id}"))
if r.status_code == 422:
raise ValidationError()
else:
r.raise_for_status()
return Product(**r.json())
def purchase_product(self, player_id: str, product_id: str) -> Product:
url = self.format_url(f"/player/{player_id}/product/purchase")
payload = {
"product_id": product_id,
}
r = requests.post(url, json=payload)
r.raise_for_status()
if r.status_code == 403:
raise PlayerInactiveError()
elif r.status_code == 404:
raise PlayerNotFoundError()
elif r.status_code == 409:
raise PositionError()
elif r.status_code == 422:
raise ValidationError()
else:
r.raise_for_status()
return Product(**r.json())