80 lines
3.3 KiB
C#
80 lines
3.3 KiB
C#
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, string? problemType = null)
|
||
: Exception(title ?? $"API vrátilo stav {(int)statusCode}.")
|
||
{
|
||
public HttpStatusCode StatusCode { get; } = statusCode;
|
||
public string? Title { get; } = title;
|
||
public string? ProblemType { get; } = problemType;
|
||
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.",
|
||
};
|
||
|
||
/// <summary>Chyby polí, pokud je API poslalo, jinak <see cref="UserMessage"/> – pro zprávu mimo formulář.</summary>
|
||
public string AllMessages => Errors.Count == 0
|
||
? UserMessage
|
||
: string.Join(" ", Errors.Values.SelectMany(messages => messages).Distinct());
|
||
|
||
public static async Task<ApiException> FromResponseAsync(HttpResponseMessage response, CancellationToken ct)
|
||
{
|
||
string? title = null;
|
||
string? type = 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;
|
||
type = problem?.Type;
|
||
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, type);
|
||
}
|
||
|
||
private sealed record ProblemBody(string? Title, Dictionary<string, string[]>? Errors, string? Type);
|
||
}
|
||
|
||
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}.");
|
||
}
|
||
}
|