Handle duplicate key error on user patch

This commit is contained in:
Peter Vacho 2025-01-03 17:11:11 +01:00
parent d19e2a5473
commit d36db8c04f
Signed by: school
GPG key ID: 8CFC3837052871B4

View file

@ -4,6 +4,7 @@ from typing import Annotated, final
from beanie import PydanticObjectId from beanie import PydanticObjectId
from fastapi import APIRouter, Body, HTTPException, Response, status from fastapi import APIRouter, Body, HTTPException, Response, status
from pydantic import BaseModel, EmailStr, StringConstraints from pydantic import BaseModel, EmailStr, StringConstraints
from pymongo.errors import DuplicateKeyError
from starlette.status import HTTP_204_NO_CONTENT from starlette.status import HTTP_204_NO_CONTENT
from src.api.auth.dependencies import LoggedInDep from src.api.auth.dependencies import LoggedInDep
@ -184,7 +185,13 @@ async def patch_user(
detail="You're not authorized to update this user", detail="You're not authorized to update this user",
) )
user = await data.update_user(user) try:
user = await data.update_user(user)
except DuplicateKeyError:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Username or email already taken",
)
return UserData.from_user(user) return UserData.from_user(user)