diff --git a/microservices/CharacterApi/Models/VisibleLocation.cs b/microservices/CharacterApi/Models/VisibleLocation.cs index 2087abf..5aff51d 100644 --- a/microservices/CharacterApi/Models/VisibleLocation.cs +++ b/microservices/CharacterApi/Models/VisibleLocation.cs @@ -1,8 +1,9 @@ -using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; +using MongoDB.Bson; namespace CharacterApi.Models; +[BsonIgnoreExtraElements] public class VisibleLocation { [BsonId] diff --git a/microservices/CharacterApi/Program.cs b/microservices/CharacterApi/Program.cs index bac4df0..7440d00 100644 --- a/microservices/CharacterApi/Program.cs +++ b/microservices/CharacterApi/Program.cs @@ -1,8 +1,9 @@ -using CharacterApi.Services; -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.IdentityModel.Tokens; -using Microsoft.OpenApi.Models; -using System.Text; +using CharacterApi.Services; +using Microsoft.AspNetCore.Diagnostics; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.IdentityModel.Tokens; +using Microsoft.OpenApi.Models; +using System.Text; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); @@ -57,11 +58,45 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) builder.Services.AddAuthorization(); -var app = builder.Build(); - -app.MapGet("/healthz", () => Results.Ok("ok")); -app.UseSwagger(); -app.UseSwaggerUI(o => +var app = builder.Build(); + +app.UseExceptionHandler(errorApp => +{ + errorApp.Run(async context => + { + var feature = context.Features.Get(); + var exception = feature?.Error; + var logger = context.RequestServices.GetRequiredService().CreateLogger("GlobalException"); + var traceId = context.TraceIdentifier; + + if (exception is not null) + { + logger.LogError( + exception, + "Unhandled exception for {Method} {Path}. TraceId={TraceId}", + context.Request.Method, + context.Request.Path, + traceId + ); + } + + context.Response.StatusCode = StatusCodes.Status500InternalServerError; + context.Response.ContentType = "application/problem+json"; + + await context.Response.WriteAsJsonAsync(new + { + type = "https://httpstatuses.com/500", + title = "Internal Server Error", + status = 500, + detail = exception?.Message ?? "An unexpected server error occurred.", + traceId + }); + }); +}); + +app.MapGet("/healthz", () => Results.Ok("ok")); +app.UseSwagger(); +app.UseSwaggerUI(o => { o.SwaggerEndpoint("/swagger/v1/swagger.json", "Character API v1"); o.RoutePrefix = "swagger";