75 lines
2.1 KiB
C#
75 lines
2.1 KiB
C#
using System.Net;
|
|
using System.Text.Json;
|
|
using AmtScanner.Api.Models;
|
|
|
|
namespace AmtScanner.Api.Middleware;
|
|
|
|
/// <summary>
|
|
/// 全局异常处理中间件
|
|
/// </summary>
|
|
public class GlobalExceptionMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
private readonly ILogger<GlobalExceptionMiddleware> _logger;
|
|
|
|
public GlobalExceptionMiddleware(RequestDelegate next, ILogger<GlobalExceptionMiddleware> 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);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 中间件扩展方法
|
|
/// </summary>
|
|
public static class GlobalExceptionMiddlewareExtensions
|
|
{
|
|
public static IApplicationBuilder UseGlobalExceptionHandler(this IApplicationBuilder app)
|
|
{
|
|
return app.UseMiddleware<GlobalExceptionMiddleware>();
|
|
}
|
|
}
|