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

77 lines
3.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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.",
};
/// <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;
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}.");
}
}