using RadicadeServer.RecNet.Responses; namespace RadicadeServer.Middleware { public class FailureEnvelopeMiddleware { private readonly RequestDelegate _next; public FailureEnvelopeMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { await _next(context); if (context.Response.HasStarted) return; var status = context.Response.StatusCode; if (status < 400 || status > 599) return; if (!string.IsNullOrEmpty(context.Response.ContentType) || context.Response.ContentLength > 0) return; await context.Response.WriteAsJsonAsync(new Failure(Why(status))); } public static string Why(int statusCode) => statusCode switch { 400 => "bad request", 401 => "unauthorized", 403 => "forbidden", 404 => "not found", 405 => "method not allowed", 408 => "request timeout", 409 => "conflict", 413 => "request too large", 415 => "unsupported media type", 422 => "unprocessable entity", 429 => "too many requests", 500 => "internal server error", 501 => "not implemented", 502 => "bad gateway", 503 => "service unavailable", 504 => "gateway timeout", _ => "request failed", }; } }