Files
idoklad/Infrastructure/ExceptionHandlingMiddleware.cs
T
JiriUhlirandClaude Opus 5 225161e4ca revize endpointu: cteni NullableProperty, filtr v UTC, attachments
Kontrola vsech 180 operaci proti falesnemu iDoklad API a round trip
331 modelu SDK v obou smerech.

- SdkNullablePropertyConverter doplnuje cteni NullableProperty<T>.
  Konvertor SDK umi jen zapis, takze PATCH s takovou polozkou koncil
  prazdnou 500 uz pri cteni tela. Tykalo se 29 modelu. Zapis zustava
  na konvertoru SDK, odchozi payload se nemeni.
- Datum uvnitr NullableProperty se normalizuje na UTC stejne jako
  zbytek serializace.
- ListModifiers parsuje datum ve filtru s AdjustToUniversal a
  AssumeUniversal. Filtr se zonou se drive posouval o offset.
- POST /attachments kontroluje FileName a FileBytes, SDK na ne sahalo
  bez kontroly na null a vracelo neosetrenou 500.
- ExceptionHandlingMiddleware ma posledni zachyt, zadny request uz
  nekonci prazdnou 500.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 11:13:21 +02:00

129 lines
5.1 KiB
C#

using System.Net;
using IdokladSdk.Exceptions;
using Microsoft.AspNetCore.Mvc;
using Idoklad.Client;
using Idoklad.Credentials;
namespace Idoklad.Infrastructure;
/// <summary>
/// Translates domain exceptions into JSON <see cref="ProblemDetails"/> responses:
/// missing credentials become 401, and upstream iDoklad failures surface the upstream status.
/// </summary>
public sealed class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (MissingCredentialsException ex)
{
await WriteProblem(context, HttpStatusCode.Unauthorized, ex.Message, new Dictionary<string, object?>
{
["missingHeaders"] = ex.MissingHeaders,
});
}
catch (IdokladApiException ex)
{
// Never log decoded credentials; only the upstream status and message.
_logger.LogWarning("iDoklad API call failed: {Status} {ErrorCode} {Message}", ex.StatusCode, ex.ErrorCode, ex.Message);
await WriteProblem(context, ex.StatusCode, ex.Message, new Dictionary<string, object?>
{
["idokladErrorCode"] = ex.ErrorCode.ToString(),
});
}
catch (IdokladAuthenticationException ex)
{
// OAuth2 token acquisition failed (bad client id/secret/application id).
_logger.LogWarning("iDoklad authentication failed: {Error}", ex.AuthenticationError?.Error ?? ex.Message);
await WriteProblem(context, HttpStatusCode.Unauthorized, ex.AuthenticationError?.ErrorDescription ?? ex.Message, new Dictionary<string, object?>
{
["idokladError"] = ex.AuthenticationError?.Error,
});
}
catch (IdokladValidationException ex)
{
// The SDK validates Post/Patch models before sending them. This does not derive from
// IdokladBaseException, so without this catch the request ended as an empty 500.
_logger.LogWarning("iDoklad model validation failed: {Message}", ex.Message);
await WriteProblem(context, HttpStatusCode.BadRequest, ex.Message, new Dictionary<string, object?>
{
["invalidProperties"] = ex.InvalidProperties?.Keys.ToArray(),
});
}
catch (IdokladBaseException ex)
{
// Other SDK-level failures (malformed responses, batch errors, etc.).
_logger.LogWarning("iDoklad SDK error: {Message}", ex.Message);
await WriteProblem(context, HttpStatusCode.BadGateway, ex.Message, null);
}
catch (HttpRequestException ex)
{
// The iDoklad API / identity server is unreachable.
_logger.LogWarning(ex, "iDoklad API unreachable.");
await WriteProblem(context, HttpStatusCode.BadGateway, "iDoklad API is unreachable.", null);
}
catch (ArgumentException ex)
{
// Thrown by the SDK when required credential fields are blank/invalid.
await WriteProblem(context, HttpStatusCode.BadRequest, ex.Message, null);
}
catch (Exception ex)
{
// Last resort: without this the response is a 500 with an empty body, which tells the
// caller nothing. The exception type is enough to locate the cause in the container log;
// no stack trace or request data is exposed.
_logger.LogError(ex, "Unhandled error while processing the request.");
await WriteProblem(context, HttpStatusCode.InternalServerError, $"Unexpected error ({ex.GetType().Name}). See the service log for details.", null);
}
}
private static async Task WriteProblem(HttpContext context, HttpStatusCode status, string detail, IDictionary<string, object?>? extensions)
{
if (context.Response.HasStarted)
{
return;
}
var problem = new ProblemDetails
{
Status = (int)status,
Title = ReasonPhrase(status),
Detail = detail,
};
if (extensions is not null)
{
foreach (var (key, value) in extensions)
{
problem.Extensions[key] = value;
}
}
context.Response.Clear();
context.Response.StatusCode = (int)status;
context.Response.ContentType = "application/problem+json";
await context.Response.WriteAsJsonAsync(problem);
}
private static string ReasonPhrase(HttpStatusCode status) => status switch
{
HttpStatusCode.Unauthorized => "Unauthorized",
HttpStatusCode.BadRequest => "Bad Request",
HttpStatusCode.BadGateway => "Upstream iDoklad API error",
HttpStatusCode.InternalServerError => "Internal Server Error",
_ => status.ToString(),
};
}