Files
Febe/src/Febe.Web/Api/ApiErrorMiddleware.cs
T

96 lines
4.2 KiB
C#

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;
/// <summary>
/// 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).
/// </summary>
public sealed class ApiErrorMiddleware(RequestDelegate next, ILogger<ApiErrorMiddleware> 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);
}
}
/// <summary>The Italian message of an argument error, without the « (Parameter 'x')» that .NET appends.</summary>
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;
}
}
/// <summary>Small helpers of the endpoints.</summary>
public static class ApiHttp
{
/// <summary>Reads a JSON body with its source-generated metadata; an empty or unreadable body is a 400.</summary>
public static async Task<T> BodyAsync<T>(HttpContext context, JsonTypeInfo<T> 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.");
}
}
/// <summary>A JSON answer with its source-generated metadata.</summary>
public static IResult Json<T>(T value, JsonTypeInfo<T> 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);
}