add(filter): 新增全局错误拦截器
This commit is contained in:
parent
82652efed7
commit
3725af7952
38
backend/IM_API/Filters/GlobalExceptionFilter.cs
Normal file
38
backend/IM_API/Filters/GlobalExceptionFilter.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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
Loading…
Reference in New Issue
Block a user