Files
NTBug/web/Helpdesk.Web/Api/ApiException.cs
T

71 lines
2.9 KiB
C#
Raw Normal View History

using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
namespace Helpdesk.Web.Api;
/// <summary>
/// Neúspěšná odpověď API ve formátu ProblemDetails (RFC 9457). Nese stav, titulek
/// a u validačních chyb seznam chyb podle polí (klíče jsou názvy vlastností v camelCase).
/// </summary>
public sealed class ApiException(HttpStatusCode statusCode, string? title, IReadOnlyDictionary<string, string[]> errors)
: Exception(title ?? $"API vrátilo stav {(int)statusCode}.")
{
public HttpStatusCode StatusCode { get; } = statusCode;
public string? Title { get; } = title;
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
/// <summary>Text pro uživatele. API píše titulky chyb česky, kromě odpovědí bez těla (např. 429).</summary>
public string UserMessage => StatusCode switch
{
HttpStatusCode.TooManyRequests => "Příliš mnoho pokusů. Zkuste to prosím za minutu.",
_ when !string.IsNullOrWhiteSpace(Title) => Title,
HttpStatusCode.Forbidden => "K této akci nemáte oprávnění.",
HttpStatusCode.NotFound => "Záznam nebyl nalezen.",
_ => "Požadavek se nepodařilo zpracovat. Zkuste to prosím znovu.",
};
public static async Task<ApiException> FromResponseAsync(HttpResponseMessage response, CancellationToken ct)
{
string? title = null;
Dictionary<string, string[]> errors = new(StringComparer.OrdinalIgnoreCase);
if (response.Content.Headers.ContentType?.MediaType is { } mediaType && mediaType.Contains("json", StringComparison.OrdinalIgnoreCase))
{
try
{
var problem = await response.Content.ReadFromJsonAsync<ProblemBody>(ct);
title = problem?.Title;
if (problem?.Errors is { } fieldErrors)
{
foreach (var (field, messages) in fieldErrors)
errors[field] = messages;
}
}
catch (JsonException)
{
// Tělo není ProblemDetails – zůstane jen stavový kód.
}
}
return new ApiException(response.StatusCode, title, errors);
}
private sealed record ProblemBody(string? Title, Dictionary<string, string[]>? Errors);
}
internal static class ApiResponse
{
public static async Task EnsureSuccessAsync(HttpResponseMessage response, CancellationToken ct)
{
if (!response.IsSuccessStatusCode)
throw await ApiException.FromResponseAsync(response, ct);
}
public static async Task<T> ReadAsync<T>(HttpResponseMessage response, CancellationToken ct)
{
await EnsureSuccessAsync(response, ct);
return await response.Content.ReadFromJsonAsync<T>(ct)
?? throw new InvalidOperationException($"API vrátilo prázdnou odpověď místo {typeof(T).Name}.");
}
}