每个代码段都去写 try catch 当然不可取,因为总会有疏漏的地方吧,如果有些遗留,那么很容易造成 bug 无迹可循,甚至有时候看windows日志也看不到痕迹,现在就考虑做一个统一处理异常并捕获的地方
建立一个类,ExceptionHandlingMiddleware 作为异常处理的中间件
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
public ExceptionHandlingMiddleware(
RequestDelegate next,
ILogger<ExceptionHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception exception)
{
_logger.LogError(
exception, "Exception occurred: {Message}", exception.Message);
var problemDetails = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "Server Error",
Detail = exception.Message
};
context.Response.StatusCode =
StatusCodes.Status500InternalServerError;
await context.Response.WriteAsJsonAsync(problemDetails);
}
}
}
在 program.cs 里注册这个中间件
var app = builder.Build();
app.UseMiddleware<ExceptionHandlingMiddleware>();