using FluentValidation; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Mvc; using NTP.Application.Common; using Oracle.ManagedDataAccess.Client; namespace NTP.Api.ErrorHandling; /// /// Turns exceptions into RFC 7807 ProblemDetails. Oracle error codes are translated so clients /// get meaningful 4xx/503 responses instead of a generic 500 - and raw ORA- text never leaks /// outside Development. /// internal sealed class GlobalExceptionHandler( IProblemDetailsService problemDetails, IHostEnvironment env, ILogger logger) : IExceptionHandler { public async ValueTask TryHandleAsync(HttpContext http, Exception exception, CancellationToken ct) { var (status, title, detail, errors) = Map(exception); if (status >= 500) logger.LogError(exception, "Unhandled error: {Title}", title); else logger.LogWarning("Request failed {Status}: {Title} - {Message}", status, title, exception.Message); ProblemDetails problem = errors is null ? new ProblemDetails() : new ValidationProblemDetails(errors); problem.Status = status; problem.Title = title; problem.Detail = detail; problem.Instance = http.Request.Path; if (exception is OracleException ora) problem.Extensions["oraCode"] = $"ORA-{ora.Number:D5}"; if (exception is BusinessException biz) problem.Extensions["code"] = biz.Code; if (env.IsDevelopment() && status >= 500) problem.Extensions["exception"] = exception.ToString(); http.Response.StatusCode = status; return await problemDetails.TryWriteAsync(new ProblemDetailsContext { HttpContext = http, ProblemDetails = problem, Exception = exception }); } private static (int Status, string Title, string? Detail, IDictionary? Errors) Map(Exception ex) => ex switch { ValidationException v when v.Errors.Any() => (400, "Validation failed", null, v.Errors.GroupBy(e => e.PropertyName) .ToDictionary(g => g.Key, g => g.Select(e => e.ErrorMessage).ToArray())), ValidationException v => (400, "Validation failed", v.Message, null), // Business rules: Title/Detail carry the legacy (Arabic) user-facing message; "code" extension is stable. AuthenticationFailedException af => (401, af.Message, af.Message, null), ForbiddenException fe => (403, fe.Message, fe.Message, null), BusinessException be => (422, be.Message, be.Message, null), NotFoundException nf => (404, "Not found", nf.Message, null), ConcurrencyException cc => (409, "Concurrency conflict", cc.Message, null), OracleException ora => MapOracle(ora), OperationCanceledException => (499, "Request cancelled", null, null), _ => (500, "Unexpected server error", null, null) }; private static (int, string, string?, IDictionary?) MapOracle(OracleException ora) => ora.Number switch { 1 => (409, "Duplicate value", "A record with the same unique key already exists.", null), // ORA-00001 2291 => (409, "Related record not found", "A referenced parent record does not exist.", null), // ORA-02291 2292 => (409, "Record in use", "The record is referenced by other records and cannot be removed.", null), // ORA-02292 1400 => (400, "Missing required value", "A required column was null.", null), // ORA-01400 12899 => (400, "Value too large", "A value exceeds the column size.", null), // ORA-12899 1438 => (400, "Number too large", "A numeric value exceeds the column precision.", null), // ORA-01438 54 or 30006 => (409, "Record locked", "The record is locked by another session. Retry shortly.", null), // ORA-00054 1013 => (504, "Database timeout", "The database operation timed out.", null), // ORA-01013 // Connectivity / instance availability 3113 or 3114 or 3135 or 12170 or 12514 or 12528 or 12537 or 12541 or 12543 or 1033 or 1034 or 1089 => (503, "Database unavailable", "The database is temporarily unavailable.", null), _ => (500, "Database error", null, null) }; }