From d36db8c04fa2aa5083f9302de320510f1019842f Mon Sep 17 00:00:00 2001 From: Peter Vacho Date: Fri, 3 Jan 2025 17:11:11 +0100 Subject: [PATCH] Handle duplicate key error on user patch --- src/api/users.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/api/users.py b/src/api/users.py index d26caa0..93a5fe9 100644 --- a/src/api/users.py +++ b/src/api/users.py @@ -4,6 +4,7 @@ from typing import Annotated, final from beanie import PydanticObjectId from fastapi import APIRouter, Body, HTTPException, Response, status from pydantic import BaseModel, EmailStr, StringConstraints +from pymongo.errors import DuplicateKeyError from starlette.status import HTTP_204_NO_CONTENT from src.api.auth.dependencies import LoggedInDep @@ -184,7 +185,13 @@ async def patch_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)