除了来自 EF core 的异常之外,几乎所有异常都会被捕获。异常过滤器正在捕获任何错误。但不是来自实体框架的错误。如果您需要任何其他信息,例如 efcore 模型等,我可以提供,但它会变得很长。
这是我的异常过滤器
public class CustomExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
Exception ex = context.Exception;
if (context.Exception is IndexOutOfRangeException)
context.Result = new OkObjectResult(new { error = true, errorMessage = ex.Message });
else if (context.Exception is ArgumentOutOfRangeException)
context.Result = new OkObjectResult(new { error = true, errorMessage = ex.Message });
else if(context.Exception is AggregateException)
context.Result = new OkObjectResult(new { error = true, errorMessage = ex.Message });
}
}
这是配置服务方法
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(options=> {
options.Filters.Add<ProductTypeSeedFilter>();
options.Filters.Add<CustomExceptionFilter>();
options.Filters.Add<VehicleSeedFilter>();
});
services.AddDbContext<InventoryContext>(options =>
options.UseSqlServer (Configuration.GetConnectionString( "DefaultConnection")),ServiceLifetime.Transient
);
services.AddSingleton<IProductService, ProductService>();
services.AddSingleton<IVehicleService, VehicleService>();
services.AddTransient<IVehicleRepository, VehicleRepository>();
services.AddTransient<IProductRepository, ProductRepository>();
services.AddMvc(o => { o.Filters.Add<CustomExceptionFilter>(); });
services.AddControllers().AddJsonOptions(options =>
options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve
);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "InventoryAPI2", Version = "v1" });
});
}
这是存储库方法。我试图通过插入 Product ean 的现有 EAN 来生成错误。
public async Task<int> InsertProduct(ProductDTO productDTO)
{
Product p = new Product()
{
EAN = productDTO.EAN,
Description = productDTO.Description,
MinimumRetail = productDTO.MinimumRetail,
MultipackUnits = productDTO.MultipackUnits,
Packsize = productDTO.PackSize,
QtyOnHand = productDTO.QtyOnHand,
RetailPrice = productDTO.RetailPrice,
CreatedDate = DateTime.Now,
UpdateDate = DateTime.Now,
HubNo = productDTO.Store,
tableKey = productDTO.datakey,
Store = _dbcontext.Stores.Where(x => x.HubNo == productDTO.Store).FirstOrDefault()
};
_dbcontext.Products.Add(p);
//if (_dbcontext.Products.Where(x => x.EAN == p.EAN).Count() < 1)
// _dbcontext.Products.Add(p);
await _dbcontext.SaveChangesAsync();
return _dbcontext.Products.Count();
}
这是控制器操作方法。
[HttpPost]
[CustomExceptionFilter]
public IActionResult Post([FromBody] ProductDTO productDTO)
{
return Ok( new { cnt =_productRepository.InsertProduct(productDTO) });
}
有人可以帮我吗?
在异常过滤器中,您没有考虑异常类型DbUpdateException
保存更改时 DbContext 抛出异常 数据库失败。请注意,此异常引用的状态条目 由于安全性和对状态条目的访问,未序列化 序列化后将返回null。
即在您的条件中添加此内容:
else if (context.Exception is DbUpdateException)
context.Result = new OkObjectResult(new { error = true, errorMessage = ex.Message });