一、局部異常處理:
在Action里面catch

二、全局異常處理:
1、默認的異常處理配置:
默認配置在StartUp文件的Configure中注冊錯誤處理,顯示開發者錯誤頁面:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } }

2、 使用 UseExceptionHandler 處理
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //app.UseDeveloperExceptionPage();//返回錯誤頁面,如果做api就不適合了 app.UseExceptionHandler(builder=> { builder.Run(async context => { context.Response.StatusCode = StatusCodes.Status500InternalServerError; context.Response.ContentType = "application/json"; var ex = context.Features.Get<IExceptionHandlerFeature>(); if (ex != null) { //記錄日志 } await context.Response.WriteAsync(ex?.Error?.Message ?? "an error occure"); }); }); app.UseHttpsRedirection(); app.UseMvc(); }
封裝成擴展方法,使用app.use...調用:
public static class ExceptionHandlingExtensions { public static void UseMyExceptionHandler(this IApplicationBuilder app,ILoggerFactory loggerFactory) { app.UseExceptionHandler(builder => { builder.Run(async context => { context.Response.StatusCode = StatusCodes.Status500InternalServerError; context.Response.ContentType = "application/json"; var ex = context.Features.Get<IExceptionHandlerFeature>(); if (ex != null) { //記錄日志 var logger = loggerFactory.CreateLogger("BlogDemo.Api.Extensions.ExceptionHandlingExtensions"); logger.LogDebug(500, ex.Error, ex.Error.Message); } await context.Response.WriteAsync(ex?.Error?.Message ?? "an error occure"); }); }); } }
public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory) { //app.UseDeveloperExceptionPage();//返回錯誤頁面,如果做api就不適合了 app.UseMyExceptionHandler(loggerFactory); app.UseHttpsRedirection(); app.UseMvc(); }
