Browse Source

增加一个错误提示中间件

master
秦汉 2 weeks ago
parent
commit
d3f7813658
  1. 16
      Build_God_Api/Build_God_Api/Program.cs

16
Build_God_Api/Build_God_Api/Program.cs

@ -190,6 +190,22 @@ namespace Build_God_Api
var app = builder.Build();
// 全局异常处理 - 只返回错误消息,不返回堆栈
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json";
var exceptionHandlerPathFeature = context.Features.Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerPathFeature>();
var exception = exceptionHandlerPathFeature?.Error;
var result = System.Text.Json.JsonSerializer.Serialize(new { message = exception?.Message ?? "服务器内部错误" });
await context.Response.WriteAsync(result);
});
});
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{

Loading…
Cancel
Save