| | | 1 | | // SPDX-FileCopyrightText: 2026 Alper Çelik <[email protected]> |
| | | 2 | | // |
| | | 3 | | // SPDX-License-Identifier: AGPL-3.0-or-later |
| | | 4 | | |
| | | 5 | | using Api.Database; |
| | | 6 | | using HotChocolate; |
| | | 7 | | using Npgsql; |
| | | 8 | | |
| | | 9 | | namespace Api.Utils; |
| | | 10 | | |
| | | 11 | | public static class DbExceptionUtils |
| | | 12 | | { |
| | | 13 | | /// <summary> |
| | | 14 | | /// Saves changes; when PostgreSQL reports an error with <paramref name="sqlState"/> |
| | | 15 | | /// (<see langword="null"/> matches any PostgreSQL error), throws a |
| | | 16 | | /// <see cref="DomainException"/> tagged with <paramref name="code"/>/<paramref name="message"/> |
| | | 17 | | /// instead of the raw database error. |
| | | 18 | | /// </summary> |
| | | 19 | | public static async Task SaveChangesOrThrowAsync( |
| | | 20 | | this PGContext db, |
| | | 21 | | string? sqlState, |
| | | 22 | | string code, |
| | | 23 | | string message, |
| | | 24 | | CancellationToken ct |
| | | 25 | | ) |
| | 1 | 26 | | { |
| | | 27 | | try |
| | 1 | 28 | | { |
| | 1 | 29 | | await db.SaveChangesAsync(cancellationToken: ct); |
| | 1 | 30 | | } |
| | 1 | 31 | | catch (Exception ex) when (TryGetPostgresException(ex, out var pg)) |
| | 1 | 32 | | { |
| | 1 | 33 | | if (sqlState is not null && sqlState != pg.SqlState) |
| | 0 | 34 | | { |
| | 0 | 35 | | throw; |
| | | 36 | | } |
| | | 37 | | |
| | 1 | 38 | | throw new DomainException(code, message); |
| | | 39 | | } |
| | 1 | 40 | | } |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// Unwraps the PostgreSQL error behind an EF Core save failure, if there is one. |
| | | 44 | | /// </summary> |
| | | 45 | | public static bool TryGetPostgresException(Exception ex, out PostgresException pg) |
| | 1 | 46 | | { |
| | 1 | 47 | | while (true) |
| | 1 | 48 | | { |
| | 1 | 49 | | if (ex is PostgresException postgres) |
| | 1 | 50 | | { |
| | 1 | 51 | | pg = postgres; |
| | 1 | 52 | | return true; |
| | | 53 | | } |
| | | 54 | | |
| | 1 | 55 | | if (ex.InnerException is null) |
| | 0 | 56 | | { |
| | 0 | 57 | | pg = null!; |
| | 0 | 58 | | return false; |
| | | 59 | | } |
| | | 60 | | |
| | 1 | 61 | | ex = ex.InnerException; |
| | 1 | 62 | | } |
| | 1 | 63 | | } |
| | | 64 | | } |