Files
AutopilotMonitor/src/Backend/AutopilotMonitor.Functions/Middleware/GlobalExceptionMiddleware.cs
T
Oliver Kieselbach 7cef2ea361 backend: one typed error envelope (IApiErrorResponse) on every non-2xx body
Every error body now leads with { error, code, correlationId }: the generic
ApiErrorResponse (hint?, retryAfterSeconds?, operation?) plus the specialised
McpQuotaExceededResponse (reordered; `message` became `error`),
DelegatedSlotLimitReachedResponse (+correlationId) and the new
SessionDeletionRejectedResponse (replaces the anonymous delete arms). The
correlation id is stamped by the writers — ResponseHelper.ErrorAsync and the
new ApiErrorWriter for the middleware side (auth 401, policy 403/503, rate
limit 429, MCP quota 429, global exception 500) — never by call sites.
exceptionType and rateLimitInfo leave the wire; Constants.ApiErrorCodes is the
code vocabulary and is exported as the manifest section `apiErrorCodes`
(API_ERROR_CODES for web + MCP). CorrelationIdMiddleware names the readable
headers via Access-Control-Expose-Headers.

Guard: TypedResponseGuardTests no longer tolerates anonymous error shapes;
the 458 legacy sites in 149 files are frozen in WriteBaseline to melt down.
New facts: envelope-prefix reflection, ApiErrorWriter body/header pins,
exact-shape pins for the generic envelope and the changed specialised bodies.

Reverses the "error bodies stay anonymous" clause of D-043 (decision entry
follows with the docs stage).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 00:56:21 +02:00

63 lines
2.5 KiB
C#

using System.Net;
using Azure;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Shared;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Middleware;
using Microsoft.Extensions.Logging;
namespace AutopilotMonitor.Functions.Middleware;
/// <summary>
/// Safety-net middleware that catches any exception escaping past function-level catch blocks
/// and returns a structured error response instead of a raw 500. Placed after
/// <see cref="CorrelationIdMiddleware"/> (needs correlation ID) and before
/// <see cref="AuthenticationMiddleware"/> (catches auth-layer exceptions too).
/// MCP clients receive richer error details via the X-Client-Source header detection.
/// </summary>
public class GlobalExceptionMiddleware : IFunctionsWorkerMiddleware
{
private readonly ILogger<GlobalExceptionMiddleware> _logger;
public GlobalExceptionMiddleware(ILogger<GlobalExceptionMiddleware> logger)
{
_logger = logger;
}
public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
{
try
{
await next(context);
}
catch (Exception ex)
{
var httpContext = context.GetHttpContext();
if (httpContext == null)
throw; // Non-HTTP triggers: let it propagate to the Functions runtime
if (httpContext.Response.HasStarted)
throw; // Response already streaming: can't write a JSON body
var correlationId = context.GetCorrelationId();
var functionName = context.FunctionDefinition.Name;
_logger.LogError(ex, "Unhandled exception in {Function} [CorrelationId={CorrelationId}]",
functionName, correlationId);
var isMcp = string.Equals(
httpContext.Request.Headers["X-Client-Source"].FirstOrDefault(),
"mcp", StringComparison.OrdinalIgnoreCase);
// Same envelope as ResponseHelper.InternalServerErrorAsync: MCP clients get the
// operation + recovery hint; the CLR exception type never leaves the process.
await ApiErrorWriter.WriteAsync(
httpContext, correlationId, HttpStatusCode.InternalServerError,
Constants.ApiErrorCodes.InternalError,
ResponseHelper.SanitizeErrorMessage(ex, functionName),
hint: isMcp ? ResponseHelper.GetRecoveryHint(ex) : null,
operation: isMcp ? functionName : null);
}
}
}