Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom exception handling for pyrail package #46

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions pyrail/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""Module containing custom exception classes for the pyrail package."""


class RateLimitError(Exception):
"""Raised when the rate limit is exceeded."""

pass


class InvalidRequestError(Exception):
"""Raised for invalid requests."""

pass


class NotFoundError(Exception):
"""Raised when an endpoint is not found."""

pass
16 changes: 11 additions & 5 deletions pyrail/irail.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from aiohttp import ClientError, ClientResponse, ClientSession

from pyrail.exceptions import InvalidRequestError, NotFoundError, RateLimitError
from pyrail.models import (
CompositionApiResponse,
ConnectionsApiResponse,
Expand Down Expand Up @@ -309,13 +310,18 @@ async def _handle_response(
retry_after: int = int(response.headers.get("Retry-After", 1))
logger.warning("Rate limited, retrying after %d seconds", retry_after)
await asyncio.sleep(retry_after)
return await self._do_request(method, args)
raise RateLimitError(f"Rate limit exceeded for method {method}")
#return await self._do_request(method, args)
elif response.status == 400:
logger.error("Bad request: %s", await response.text())
return None
error_message = await response.text()
logger.error("Bad request: %s", error_message)
raise InvalidRequestError(error_message)
#return None
elif response.status == 404:
logger.error("Endpoint %s not found, response: %s", method, await response.text())
return None
error_message = await response.text()
logger.error("Endpoint %s not found, response: %s", method, error_message)
raise NotFoundError(error_message)
#return None
Comment on lines +321 to +324
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix NotFoundError handling and remove commented code.

The pipeline failure indicates an issue with NotFoundError being thrown for an invalid station. Consider improving the error message to be more specific about the type of resource that wasn't found.

             error_message = await response.text()
+            resource_type = "resource"
+            if "station" in method.lower() or "stop" in error_message.lower():
+                resource_type = "station"
+            elif "vehicle" in method.lower():
+                resource_type = "vehicle"
             logger.error("Endpoint %s not found, response: %s", method, error_message)
-            raise NotFoundError(error_message)
+            raise NotFoundError(f"{resource_type.title()} not found: {error_message}")
-            #return None
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
error_message = await response.text()
logger.error("Endpoint %s not found, response: %s", method, error_message)
raise NotFoundError(error_message)
#return None
error_message = await response.text()
resource_type = "resource"
if "station" in method.lower() or "stop" in error_message.lower():
resource_type = "station"
elif "vehicle" in method.lower():
resource_type = "vehicle"
logger.error("Endpoint %s not found, response: %s", method, error_message)
raise NotFoundError(f"{resource_type.title()} not found: {error_message}")
🧰 Tools
🪛 GitHub Actions: Run Tests

[error] 323-323: NotFoundError exception thrown: Stop 'INVALID_STATION' can not be found

elif response.status == 200:
return await self._handle_success_response(response, method)
elif response.status == 304:
Expand Down
Loading