Handle unique constraint violation on ProductCompanyTableCouple create

This commit is contained in:
martinshoob 2025-08-11 21:24:28 +02:00
parent e7b737a3dd
commit 87a2250852

View file

@ -4,6 +4,7 @@ using DrinkRateAPI.Contexts;
using DrinkRateAPI.DbEntities; using DrinkRateAPI.DbEntities;
using DrinkRateAPI.Exceptions; using DrinkRateAPI.Exceptions;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Npgsql;
namespace DrinkRateAPI.Services; namespace DrinkRateAPI.Services;
@ -24,7 +25,20 @@ public class ProductCompanyTableCoupleService(ApplicationDbContext context)
}; };
_context.CompanyTable.Add(companyTable); _context.CompanyTable.Add(companyTable);
await _context.SaveChangesAsync();
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException ex) when
(ex.InnerException is PostgresException
{
SqlState: PostgresErrorCodes.UniqueViolation
}
)
{
throw new BadRequestException("Product table or company table with the same name already exists.");
}
return await GetProductCompanyTableCouplePostResponse( return await GetProductCompanyTableCouplePostResponse(
productCompanyTableCouplePost.ProductTableName, productCompanyTableCouplePost.ProductTableName,