add(filter): 新增全局错误拦截器

This commit is contained in:
西街长安 2025-12-15 17:30:58 +08:00
parent 82652efed7
commit 3725af7952
3 changed files with 400 additions and 728 deletions

View File

@ -0,0 +1,38 @@
using IM_API.Dtos;
using IM_API.Exceptions;
using IM_API.Tools;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace IM_API.Filters
{
public class GlobalExceptionFilter : IExceptionFilter
{
private readonly ILogger<GlobalExceptionFilter> _logger;
public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
{
_logger = logger;
}
public void OnException(ExceptionContext context)
{
if(context.Exception is BaseException)
{
var exception = (BaseException)context.Exception;
BaseResponse<object?> res = new BaseResponse<object?>(
code:exception.Code,
message: exception.Message,
data:null
);
context.Result = new JsonResult(res);
}
else
{
_logger.LogError(context.Exception,context.Exception.Message);
BaseResponse<object?> res = new BaseResponse<object?>(CodeDefine.SYSTEM_ERROR);
context.Result = new JsonResult(res);
}
context.ExceptionHandled = true;
}
}
}

View File

@ -1,5 +1,6 @@
using IM_API.Configs;
using IM_API.Filters;
using IM_API.Hubs;
using IM_API.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
@ -97,7 +98,10 @@ namespace IM_API
}
};
});
builder.Services.AddControllers();
builder.Services.AddControllers(options =>
{
options.Filters.Add<GlobalExceptionFilter>();
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

File diff suppressed because it is too large Load Diff