using System.Text.Json; using System.Text.Json.Serialization.Metadata; using Febe.Core.Storage; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Febe.Web.Api; /// /// Turns the exceptions of the API into Italian answers: 400 for a wrong request, 404 for something missing, 409 for a /// duplicate, 500 with a message that says what happened (never a stack trace, never a caption or a path of the request). /// public sealed class ApiErrorMiddleware(RequestDelegate next, ILogger logger) { public async Task InvokeAsync(HttpContext context) { ArgumentNullException.ThrowIfNull(context); if (!context.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)) { await next(context).ConfigureAwait(false); return; } try { await next(context).ConfigureAwait(false); } catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested) { // The page went away: nothing to answer. } catch (Exception ex) when (!context.Response.HasStarted) { var (status, message) = ex switch { BadRequestException => (StatusCodes.Status400BadRequest, ex.Message), ArgumentException a => (StatusCodes.Status400BadRequest, CleanMessage(a)), JsonException => (StatusCodes.Status400BadRequest, "Richiesta non leggibile."), BadHttpRequestException => (StatusCodes.Status400BadRequest, "Richiesta non leggibile."), NotFoundException => (StatusCodes.Status404NotFound, ex.Message), DuplicateRecordException => (StatusCodes.Status409Conflict, ex.Message), _ => (StatusCodes.Status500InternalServerError, "Errore interno: Febe non ha completato l'operazione. Riprova; se succede ancora, guarda il registro."), }; if (status == StatusCodes.Status500InternalServerError) { // Type and message only: no request data. logger.LogError("Errore dell'API: {Type}: {Message}", ex.GetType().Name, ex.Message); } context.Response.Clear(); context.Response.StatusCode = status; await context.Response.WriteAsJsonAsync(new ProblemDto(message), FebeJsonContext.Default.ProblemDto).ConfigureAwait(false); } } /// The Italian message of an argument error, without the « (Parameter 'x')» that .NET appends. public static string CleanMessage(ArgumentException exception) { ArgumentNullException.ThrowIfNull(exception); return exception.ParamName is { } name ? exception.Message.Replace($" (Parameter '{name}')", string.Empty, StringComparison.Ordinal) : exception.Message; } } /// Small helpers of the endpoints. public static class ApiHttp { /// Reads a JSON body with its source-generated metadata; an empty or unreadable body is a 400. public static async Task BodyAsync(HttpContext context, JsonTypeInfo type) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(type); if (context.Request.ContentLength == 0) { throw new BadRequestException("Richiesta vuota."); } try { var value = await JsonSerializer.DeserializeAsync(context.Request.Body, type, context.RequestAborted).ConfigureAwait(false); return value ?? throw new BadRequestException("Richiesta vuota."); } catch (JsonException) { throw new BadRequestException("Richiesta non leggibile."); } } /// A JSON answer with its source-generated metadata. public static IResult Json(T value, JsonTypeInfo type, int status = StatusCodes.Status200OK) => Results.Json(value, type, statusCode: status); public static IResult Message(string message, int status = StatusCodes.Status200OK) => Results.Json(new MessageDto(message), FebeJsonContext.Default.MessageDto, statusCode: status); }