feat: new exceptions

This commit is contained in:
2026-10-07 02:59:23 +04:00
parent 274e60a433
commit e7e7bf4db7
13 changed files with 74 additions and 36 deletions
@@ -5,7 +5,11 @@ using Microsoft.AspNetCore.Mvc;
namespace MemeVault.Api.Middleware;
/// <summary>
/// Конвертирует DomainException в 400 Problem Details.
/// Конвертирует DomainException и наследников в Problem Details:
/// <list type="bullet">
/// <item><see cref="InsufficientPermissionException"/> → 403</item>
/// <item>Все остальные <see cref="DomainException"/> → 400</item>
/// </list>
/// </summary>
public sealed class DomainExceptionHandler : IExceptionHandler
{
@@ -17,14 +21,18 @@ public sealed class DomainExceptionHandler : IExceptionHandler
if (ex is not DomainException domain)
return false;
var status = domain is InsufficientPermissionException
? StatusCodes.Status403Forbidden
: StatusCodes.Status400BadRequest;
var problem = new ProblemDetails
{
Title = "Business rule violation",
Title = domain is InsufficientPermissionException ? "Forbidden" : "Business rule violation",
Detail = domain.Message,
Status = StatusCodes.Status400BadRequest,
Status = status,
};
ctx.Response.StatusCode = problem.Status!.Value;
ctx.Response.StatusCode = status;
await ctx.Response.WriteAsJsonAsync(problem, ct);
return true;
}
@@ -20,7 +20,7 @@ public sealed class DeleteCollectionCommandHandler(
var user = await users.GetByTelegramIdAsync(request.RequestingTelegramId, ct);
if (user?.InboxCollectionId == collection.Id)
throw new DomainException("Cannot delete the Inbox collection.");
throw new InboxProtectionException("Cannot delete the Inbox collection.");
collection.Delete(request.RequestingTelegramId);
await collections.RemoveAsync(collection, ct);
@@ -22,7 +22,7 @@ public sealed class SetCollectionInboxCommandHandler(
if (user is null) return false;
if (user.InboxCollectionId == target.Id)
throw new DomainException("Collection is already the Inbox.");
throw new InboxProtectionException("Collection is already the Inbox.");
user.SetInboxCollection(target.Id);
await users.UpdateAsync(user, ct);
@@ -1,13 +1,11 @@
using MediatR;
using MemeVault.Application.Common;
using MemeVault.Domain.Exceptions;
using MemeVault.Domain.Repositories;
namespace MemeVault.Application.Commands.UpdateCollection;
public sealed class UpdateCollectionCommandHandler(
ICollectionRepository collections,
IBotUserRepository users,
IUnitOfWork unitOfWork)
: IRequestHandler<UpdateCollectionCommand, bool>
{
@@ -15,14 +13,10 @@ public sealed class UpdateCollectionCommandHandler(
{
var collection = await collections.GetByIdAsync(request.CollectionId, ct);
// Если коллекции нет или пользователь — не участник, возвращаем 404.
// Если роль ниже Manager — domain.Rename() бросит DomainException.
// Если роль ниже Manager — domain.Rename() бросит InsufficientPermissionException.
if (collection is null || collection.GetRole(request.RequestingTelegramId) is null)
return false;
var user = await users.GetByTelegramIdAsync(request.RequestingTelegramId, ct);
if (user?.InboxCollectionId == collection.Id)
throw new DomainException("Cannot rename the Inbox collection.");
collection.Rename(request.Name, request.RequestingTelegramId);
await unitOfWork.SaveChangesAsync(ct);
return true;
@@ -13,14 +13,17 @@ public sealed class GetMediaDownloadUrlQueryHandler
private static readonly TimeSpan UrlExpiry = TimeSpan.FromMinutes(15);
private readonly IMediaItemRepository _mediaItems;
private readonly ITelegramFileCacheService _cache;
private readonly ITelegramFileCacheService _telegramCache;
private readonly IFileStorage _fileStorage;
public GetMediaDownloadUrlQueryHandler(
IMediaItemRepository mediaItems,
ITelegramFileCacheService cache)
ITelegramFileCacheService telegramCache,
IFileStorage fileStorage)
{
_mediaItems = mediaItems;
_cache = cache;
_mediaItems = mediaItems;
_telegramCache = telegramCache;
_fileStorage = fileStorage;
}
public async Task<string> Handle(GetMediaDownloadUrlQuery request, CancellationToken ct)
@@ -29,18 +32,18 @@ public sealed class GetMediaDownloadUrlQueryHandler
?? throw new DomainException("Media item not found.");
if (item.OwnerTelegramId != request.RequestingUserTelegramId)
throw new DomainException("Access denied.");
throw new InsufficientPermissionException("Access denied.");
if (item.Type == MediaType.Text || item.Source is null)
throw new DomainException("This media item has no downloadable file.");
if (item.Source.Origin == MediaOrigin.S3)
{
// Already stored in S3 — just generate a presigned URL directly.
return await _cache.GetCachedUrlAsync(item.Source.Reference!, UrlExpiry, ct);
// File is already stored in S3 — generate presigned URL directly.
return await _fileStorage.GetDownloadUrlAsync(item.Source.Reference!, UrlExpiry, ct);
}
// Telegram source — go through cache (lock → S3 check → fetch → upload → presign).
return await _cache.GetCachedUrlAsync(item.Source.Reference!, UrlExpiry, ct);
// Telegram source — fetch, cache in S3, and return presigned URL.
return await _telegramCache.GetCachedUrlAsync(item.Source.Reference!, UrlExpiry, ct);
}
}
@@ -52,10 +52,10 @@ public sealed class Collection
public static Collection Create(long ownerTelegramId, string name, string? description = null)
{
if (string.IsNullOrWhiteSpace(name))
throw new DomainException("Collection name cannot be empty.");
throw new DomainValidationException("Collection name cannot be empty.");
if (name.Length > 100)
throw new DomainException("Collection name must be 100 characters or less.");
throw new DomainValidationException("Collection name must be 100 characters or less.");
return new Collection(Guid.NewGuid(), ownerTelegramId, name, description);
}
@@ -71,7 +71,7 @@ public sealed class Collection
EnsureRole(requestingTelegramId, CollectionRole.Owner);
if (role == CollectionRole.Owner)
throw new DomainException("Cannot assign Owner role. Transfer ownership instead.");
throw new InsufficientPermissionException("Cannot assign Owner role. Transfer ownership instead.");
var existing = _members.FirstOrDefault(m => m.TelegramId == telegramId);
if (existing is not null)
@@ -129,7 +129,7 @@ public sealed class Collection
EnsureRole(requestingTelegramId, CollectionRole.Manager);
if (string.IsNullOrWhiteSpace(newName))
throw new DomainException("Collection name cannot be empty.");
throw new DomainValidationException("Collection name cannot be empty.");
Name = newName.Trim();
UpdatedAt = DateTimeOffset.UtcNow;
@@ -219,7 +219,7 @@ public sealed class Collection
{
var role = GetRole(telegramId);
if (role is null || role < minimumRole)
throw new DomainException($"Action requires at least {minimumRole} role.");
throw new InsufficientPermissionException($"Action requires at least {minimumRole} role.");
}
private static string GenerateToken() =>
@@ -52,10 +52,10 @@ public sealed class CollectionInvite
DateTimeOffset? expiresAt = null)
{
if (role == CollectionRole.Owner)
throw new DomainException("Cannot create an invite with Owner role.");
throw new InsufficientPermissionException("Cannot create an invite with Owner role.");
if (expiresAt.HasValue && expiresAt.Value <= DateTimeOffset.UtcNow)
throw new DomainException("Invite expiry must be in the future.");
throw new DomainValidationException("Invite expiry must be in the future.");
return new CollectionInvite(collectionId, createdBy, role, expiresAt);
}
@@ -75,10 +75,10 @@ public sealed class MediaItem
IEnumerable<Tag>? tags = null)
{
if (type == MediaType.Text && string.IsNullOrWhiteSpace(caption))
throw new DomainException("Text media must have non-empty caption.");
throw new DomainValidationException("Text media must have non-empty caption.");
if (type != MediaType.Text && source is null)
throw new DomainException("Non-text media must have a source (Telegram fileId or S3 key).");
throw new DomainValidationException("Non-text media must have a source (Telegram fileId or S3 key).");
var item = new MediaItem(
Guid.NewGuid(),
@@ -111,7 +111,7 @@ public sealed class MediaItem
{
if (_tags.Contains(tag)) return;
if (_tags.Count >= 20)
throw new DomainException("Cannot have more than 20 tags per item.");
throw new DomainValidationException("Cannot have more than 20 tags per item.");
_tags.Add(tag);
UpdatedAt = DateTimeOffset.UtcNow;
@@ -128,7 +128,7 @@ public sealed class MediaItem
{
var distinct = newTags.Distinct().ToList();
if (distinct.Count > 20)
throw new DomainException("Cannot have more than 20 tags per item.");
throw new DomainValidationException("Cannot have more than 20 tags per item.");
_tags.Clear();
_tags.AddRange(distinct);
@@ -0,0 +1,11 @@
namespace MemeVault.Domain.Exceptions;
/// <summary>
/// Выбрасывается при нарушении инвариантов формата данных:
/// пустые строки, превышение длины, недопустимые значения.
/// API-слой преобразует в HTTP 400.
/// </summary>
public sealed class DomainValidationException : DomainException
{
public DomainValidationException(string message) : base(message) { }
}
@@ -0,0 +1,11 @@
namespace MemeVault.Domain.Exceptions;
/// <summary>
/// Выбрасывается при попытке выполнить запрещённую операцию над Inbox-коллекцией:
/// удалить, переименовать или назначить уже активный Inbox повторно.
/// API-слой преобразует в HTTP 400.
/// </summary>
public sealed class InboxProtectionException : DomainException
{
public InboxProtectionException(string message) : base(message) { }
}
@@ -0,0 +1,11 @@
namespace MemeVault.Domain.Exceptions;
/// <summary>
/// Выбрасывается, когда у пользователя недостаточно прав для выполнения операции
/// (недостаточная роль в коллекции или полный отказ в доступе).
/// API-слой преобразует в HTTP 403.
/// </summary>
public sealed class InsufficientPermissionException : DomainException
{
public InsufficientPermissionException(string message) : base(message) { }
}
+2 -2
View File
@@ -9,12 +9,12 @@ public sealed record Tag
public Tag(string value)
{
if (string.IsNullOrWhiteSpace(value))
throw new DomainException("Tag cannot be empty.");
throw new DomainValidationException("Tag cannot be empty.");
Value = value.Trim().ToLowerInvariant();
if (Value.Length > 50)
throw new DomainException("Tag must be 50 characters or less.");
throw new DomainValidationException("Tag must be 50 characters or less.");
}
public static implicit operator string(Tag tag) => tag.Value;
@@ -13,7 +13,7 @@ public sealed record TelegramFileId
public TelegramFileId(string value)
{
if (string.IsNullOrWhiteSpace(value))
throw new DomainException("FileId cannot be empty.");
throw new DomainValidationException("FileId cannot be empty.");
Value = value;
}