Handle ObjectID conversion errors

This commit is contained in:
april
2024-01-15 09:01:21 -06:00
parent 5ab412d82a
commit d6a0eb349a
8 changed files with 65 additions and 47 deletions

17
api/utils.py Normal file
View File

@@ -0,0 +1,17 @@
from bson import ObjectId
from bson.errors import InvalidId
from fastapi import HTTPException
def to_objectid(id: str) -> ObjectId:
"""
Try to convert a given string to an ObjectId
:param id: ID in string form to convert
:return: Converted ObjectId
"""
try:
oid = ObjectId(id)
return oid
except InvalidId:
raise HTTPException(400, f"{id} is not a recognized ID")