using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Mvc; namespace JobTrackerApi.Services; public sealed class PdfRenderExceptionHandler : IExceptionHandler { public async ValueTask TryHandleAsync(HttpContext context, Exception exception, CancellationToken cancellationToken) { if (exception is not (PdfCapacityException or PdfRenderTimeoutException)) return false; var busy = exception is PdfCapacityException; var status = busy ? StatusCodes.Status503ServiceUnavailable : StatusCodes.Status504GatewayTimeout; context.Response.StatusCode = status; context.Response.Headers.CacheControl = "no-store"; if (busy) context.Response.Headers.RetryAfter = "3"; await context.Response.WriteAsJsonAsync(new ProblemDetails { Status = status, Title = busy ? "PDF generation is busy" : "PDF generation timed out", Detail = exception.Message, Extensions = { ["code"] = busy ? "pdf_capacity_exceeded" : "pdf_render_timeout", ["traceId"] = context.TraceIdentifier } }, cancellationToken); return true; } }