From 6f2fe7878097716a4929ba526f75c1d4b1c961b3 Mon Sep 17 00:00:00 2001 From: Tommaso Comparin <3862206+tcompa@users.noreply.github.com> Date: Thu, 22 Sep 2022 17:00:10 +0200 Subject: [PATCH] Better failure when task name already exists (closes #64) --- fractal_server/app/api/v1/task.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/fractal_server/app/api/v1/task.py b/fractal_server/app/api/v1/task.py index 94d352cdc..b1b8f02de 100644 --- a/fractal_server/app/api/v1/task.py +++ b/fractal_server/app/api/v1/task.py @@ -7,6 +7,7 @@ from fastapi import APIRouter from fastapi import Depends +from fastapi import HTTPException from fastapi import status from sqlalchemy.exc import IntegrityError from sqlmodel import select @@ -96,9 +97,16 @@ async def create_task( db: AsyncSession = Depends(get_db), ): db_task = Task.from_orm(task) - db.add(db_task) - await db.commit() - await db.refresh(db_task) + try: + db.add(db_task) + await db.commit() + await db.refresh(db_task) + except IntegrityError as e: + await db.rollback() + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail=str(e), + ) return db_task