DD.WellWorkover.Cloud/AsbCloudDb/EFExtensionsExceptionHandling.cs

35 lines
1.1 KiB
C#
Raw Normal View History

using AsbCloudDb.Model;
2024-02-08 11:38:25 +05:00
using Microsoft.EntityFrameworkCore;
using Npgsql;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudDb
{
public static class EFExtensionsExceptionHandling
{
public static async Task<int> SaveChangesWithExceptionHandling(this IAsbCloudDbContext db, CancellationToken token)
{
try
{
var result = await db.SaveChangesAsync(token);
return result;
}
catch (DbUpdateException ex)
{
if (ex.InnerException is PostgresException pgException)
TryConvertPostgresExceptionToValidateException(pgException);
throw;
}
}
private static void TryConvertPostgresExceptionToValidateException(PostgresException pgException)
{
if (pgException.SqlState == PostgresErrorCodes.ForeignKeyViolation)
2024-02-12 13:58:02 +05:00
// TODO: replace ArgumentException by new Exception
2024-02-08 11:38:25 +05:00
throw new ArgumentException(pgException.Message + "\r\n" + pgException.Detail, "dtos");
}
}
}