using System.Net;
using System.Text.Json;
using AmtScanner.Api.Models;
namespace AmtScanner.Api.Middleware;
///
/// 全局异常处理中间件
///
public class GlobalExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public GlobalExceptionMiddleware(RequestDelegate next, ILogger logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
_logger.LogError(exception, "An unhandled exception occurred: {Message}", exception.Message);
var response = context.Response;
response.ContentType = "application/json";
var (statusCode, code, message) = exception switch
{
UnauthorizedAccessException => (HttpStatusCode.Unauthorized, 401, "未授权访问"),
ArgumentException argEx => (HttpStatusCode.BadRequest, 400, argEx.Message),
KeyNotFoundException => (HttpStatusCode.NotFound, 404, "资源不存在"),
InvalidOperationException invEx => (HttpStatusCode.BadRequest, 400, invEx.Message),
_ => (HttpStatusCode.InternalServerError, 500, "服务器内部错误")
};
response.StatusCode = (int)statusCode;
var result = JsonSerializer.Serialize(new ApiResponse
{
Code = code,
Msg = message,
Data = null
}, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
await response.WriteAsync(result);
}
}
///
/// 中间件扩展方法
///
public static class GlobalExceptionMiddlewareExtensions
{
public static IApplicationBuilder UseGlobalExceptionHandler(this IApplicationBuilder app)
{
return app.UseMiddleware();
}
}