代码如下:
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Newtonsoft.Json.Serialization; using Simple_Asp.Net_Core.Data; using Simple_Asp.Net_Core.ServiceProvider; using System; namespace Simple_Asp.Net_Core { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddJWT(); services.AddDbContext<CommanderContext>(options => options.UseNpgsql("Host=localhost;Database=postgres;Username=postgres;Password=123456")); services.AddCORS(); services.AddMvc(); services.AddSwagger(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddScoped<ICommanderRepo, SqlCommanderRepo>(); services.AddControllers().AddNewtonsoftJson(s => { s.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1"); }); } app.UseExceptionHandler(builder => builder.Run(async context => await ExceptionHandler.ErrorEvent(context))); app.UseCors("CorsTest"); app.UseAuthentication(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute()); } } } 启动项目,调用api/commands/{id}接口,可以看出后端的接口发生了异常,此时的异常比较清晰。 最后我们将SqlCommanderRepo.cs里的异常改为友好异常 再次修改SqlCommanderRepo.cs代码调整如下:
using Simple_Asp.Net_Core.Models; using Simple_Asp.Net_Core.ServiceProvider; using System; using System.Collections.Generic; using System.Linq; namespace Simple_Asp.Net_Core.Data { public class SqlCommanderRepo : ICommanderRepo { private readonly CommanderContext _context; public SqlCommanderRepo(CommanderContext context) { _context = context; } public void CreateCommand(Command cmd) { if (cmd == null) { throw new ArgumentNullException(nameof(cmd)); } _context.Commands.Add(cmd); } public void DeleteCommand(Command cmd) { if (cmd == null) { throw new ArgumentNullException(nameof(cmd)); } _context.Commands.Remove(cmd); } public IEnumerable<Command> GetAllCommands() { return _context.Commands.ToList(); } public Command GetCommandById(int id) { if (id == 0) throw new Exception("id不能为0!"); return _context.Commands.First(p => p.Id == id); } public bool SaveChanges() { return (_context.SaveChanges() >= 0); } public void UpdateCommand(Command cmd) { //Nothing } } } 最后启动项目,调用api/commands/{id}接口,这时候我们可以得到友好的提示! 总结本文为Simple项目增加异常处理与使用友好异常(UserFriendlyException),在捕捉到程序异常的时候需要写入日志方便问题追踪!
目前Simple项目还未使用日志组件,后续会补上
异常捕捉为了能够将异常内容进行收集,并且能以统一的方式返回给客户端。保证服务器的安全、帮助我们追踪问题并且客户端的体验也能有所保证。
异常捕捉结合友好异常的方式能够为我们减少代码量,并且让代码更直观明了,推荐大家一试!
GitHub源码注意:源码调试过程中如果出现xml文件路径错误,需要参照第一章(后端项目搭建与Swagger配置步骤)Swagger配置“配置XML 文档文件”步骤,取消勾选然后再选中 ,将XML路径设置成与你的电脑路径匹配!
https://github.com/Impartsoft/Simple_Asp.Net_Core/tree/master/Simple_Asp.Net_Core 6.Exception Handling %26 UserFriendlyException
参考资料ABP开源项目异常处理 https://docs.abp.io/zh-Hans/abp/latest/Exception-Handling