Changeset acf690c for ChapterX.API/Program.cs
- Timestamp:
- 03/22/26 17:58:40 (4 months ago)
- Branches:
- main
- Children:
- 73b69b2
- Parents:
- b62cefc
- File:
-
- 1 edited
-
ChapterX.API/Program.cs (modified) (3 diffs)
Legend:
- Unmodified
- Added
- Removed
-
ChapterX.API/Program.cs
rb62cefc racf690c 16 16 }); 17 17 18 builder.Services.AddControllers(); 18 builder.Services.AddControllers() 19 .AddJsonOptions(options => 20 { 21 options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles; 22 }); 19 23 builder.Services.AddEndpointsApiExplorer(); 20 24 builder.Services.AddSwaggerGen(options => … … 68 72 var app = builder.Build(); 69 73 74 app.UseCors("Frontend"); 75 70 76 if (app.Environment.IsDevelopment()) 71 77 { … … 74 80 } 75 81 76 app.UseHttpsRedirection(); 77 app.UseCors("Frontend"); 82 app.UseExceptionHandler(err => err.Run(async ctx => 83 { 84 var ex = ctx.Features.Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerFeature>()?.Error; 85 ctx.Response.ContentType = "application/json"; 86 87 string message; 88 int status; 89 90 if (ex is UnauthorizedAccessException) 91 { 92 status = 401; 93 message = ex.Message; 94 } 95 else if (ex is InvalidOperationException) 96 { 97 status = 400; 98 message = ex.Message; 99 } 100 else if (ex is Microsoft.EntityFrameworkCore.DbUpdateException dbEx) 101 { 102 status = 400; 103 var inner = dbEx.InnerException?.Message ?? ""; 104 if (inner.Contains("email_format")) 105 message = "Invalid email format."; 106 else if (inner.Contains("unique") || inner.Contains("duplicate") || inner.Contains("23505")) 107 message = "A user with this email or username already exists."; 108 else 109 message = "Database error: " + inner; 110 } 111 else 112 { 113 status = 500; 114 message = ex?.Message ?? "An error occurred."; 115 } 116 117 ctx.Response.StatusCode = status; 118 await ctx.Response.WriteAsJsonAsync(new { message }); 119 })); 120 78 121 app.UseAuthentication(); 79 122 app.UseAuthorization();
Note:
See TracChangeset
for help on using the changeset viewer.
