Skip to content

Commit a9ccb21

Browse files
committed
Clean up of unnecessary excepts #176
1 parent 2326535 commit a9ccb21

File tree

5 files changed

+28
-35
lines changed

5 files changed

+28
-35
lines changed

object_storage_api/core/custom_object_id.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,17 +20,29 @@ class CustomObjectId(ObjectId):
2020
purpose of handling MongoDB `_id` fields that are of type `ObjectId`.
2121
"""
2222

23-
def __init__(self, value: str, entity_type: Optional[str] = None, not_found_if_invalid: bool = False):
23+
def __init__(
24+
self,
25+
value: str,
26+
entity_type: Optional[str] = None,
27+
not_found_if_invalid: bool = False,
28+
response_detail: Optional[str] = None,
29+
):
2430
"""
2531
Construct a `CustomObjectId` from a string.
2632
2733
:param value: The string value to be validated, representing the `ObjectId`.
2834
:param entity_type: Name of the entity type e.g. catalogue categories/systems (Used for logging).
2935
:param not_found_if_invalid: Whether an error due to an invalid ID should be raised as a not found error
30-
or not. Unprocessable entity is used if left as the default value False.
36+
or not. Unprocessable entity is used if left as the default value False.
37+
:param response_detail: Response detail to return in the the request if uncaught, overrides any error message
38+
constructed by the other parameters.
3139
:raises InvalidObjectIdError: If the string value is an invalid `ObjectId`.
3240
"""
33-
response_detail = None if entity_type is None else f"{entity_type.capitalize()} not found"
41+
response_detail = (
42+
response_detail
43+
if response_detail is not None
44+
else (None if entity_type is None else f"{entity_type.capitalize()} not found")
45+
)
3446
status_code = status.HTTP_404_NOT_FOUND if not_found_if_invalid else None
3547

3648
if not isinstance(value, str):

object_storage_api/repositories/attachment.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -62,16 +62,10 @@ def get(self, attachment_id: str, session: Optional[ClientSession] = None) -> Op
6262
"""
6363

6464
logger.info("Retrieving attachment with ID: %s from the database", attachment_id)
65-
66-
try:
67-
attachment = self._attachments_collection.find_one(
68-
{"_id": CustomObjectId(attachment_id, entity_type="attachment", not_found_if_invalid=True)},
69-
session=session,
70-
)
71-
except InvalidObjectIdError as exc:
72-
exc.status_code = 404
73-
exc.response_detail = "Attachment not found"
74-
raise exc
65+
attachment = self._attachments_collection.find_one(
66+
{"_id": CustomObjectId(attachment_id, entity_type="attachment", not_found_if_invalid=True)},
67+
session=session,
68+
)
7569

7670
if attachment:
7771
return AttachmentOut(**attachment)

object_storage_api/repositories/image.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -60,14 +60,10 @@ def get(self, image_id: str, session: Optional[ClientSession] = None) -> ImageOu
6060
:raises InvalidObjectIdError: If the supplied `image_id` is invalid.
6161
"""
6262
logger.info("Retrieving image with ID: %s from the database", image_id)
63-
try:
64-
image = self._images_collection.find_one(
65-
{"_id": CustomObjectId(image_id, entity_type="image", not_found_if_invalid=True)}, session=session
66-
)
67-
except InvalidObjectIdError as exc:
68-
exc.status_code = 404
69-
exc.response_detail = "Image not found"
70-
raise exc
63+
image = self._images_collection.find_one(
64+
{"_id": CustomObjectId(image_id, entity_type="image", not_found_if_invalid=True)}, session=session
65+
)
66+
7167
if image:
7268
return ImageOut(**image)
7369
raise MissingRecordError(entity_id=image_id, entity_type="image")

object_storage_api/services/attachment.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
from object_storage_api.core.custom_object_id import CustomObjectId
1616
from object_storage_api.core.exceptions import (
1717
FileTypeMismatchException,
18-
InvalidObjectIdError,
1918
UnsupportedFileExtensionException,
2019
UploadLimitReachedError,
2120
)
@@ -63,12 +62,8 @@ def create(self, attachment: AttachmentPostSchema) -> AttachmentPostResponseSche
6362
:raises UnsupportedFileExtensionException: If the file extension of the attachment is not supported.
6463
:raises UploadLimitReachedError: If the upload limit has been reached.
6564
"""
66-
try:
67-
CustomObjectId(attachment.entity_id)
68-
except InvalidObjectIdError as exc:
69-
# Provide more specific detail
70-
exc.response_detail = "Invalid `entity_id` given"
71-
raise exc
65+
# Check the entity ID is valid
66+
CustomObjectId(attachment.entity_id, response_detail="Invalid `entity_id` given")
7267

7368
file_extension = Path(attachment.file_name).suffix
7469
if not file_extension or file_extension.lower() not in config.attachment.allowed_file_extensions:

object_storage_api/services/image.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
from object_storage_api.core.custom_object_id import CustomObjectId
1616
from object_storage_api.core.exceptions import (
1717
FileTypeMismatchException,
18-
InvalidObjectIdError,
1918
UnsupportedFileExtensionException,
2019
UploadLimitReachedError,
2120
)
@@ -65,12 +64,9 @@ def create(self, image_metadata: ImagePostMetadataSchema, upload_file: UploadFil
6564
:raises FileTypeMismatchException: If the extension and content type of the image do not match.
6665
:raises UploadLimitReachedError: If the upload limit has been reached.
6766
"""
68-
try:
69-
CustomObjectId(image_metadata.entity_id)
70-
except InvalidObjectIdError as exc:
71-
# Provide more specific detail
72-
exc.response_detail = "Invalid `entity_id` given"
73-
raise exc
67+
68+
# Check the entity ID is valid
69+
CustomObjectId(image_metadata.entity_id, response_detail="Invalid `entity_id` given")
7470

7571
file_extension = Path(upload_file.filename).suffix
7672
if not file_extension or file_extension.lower() not in config.image.allowed_file_extensions:

0 commit comments

Comments
 (0)