經過全局異常類,全部程序中遇到的錯誤都會被攔截,並友好的返回結果。json
一、自定義一個全局異常處理類中間件app
using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Xml.Serialization; using UFX.Mall.EntityModel; using UFX.Tools; namespace UFX.Mall.WebApi { public class ExceptionHandlerMiddleWare { private readonly RequestDelegate next; public ExceptionHandlerMiddleWare(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext context) { try { await next(context); } catch (Exception ex) { await HandleExceptionAsync(context, ex); } } private static async Task HandleExceptionAsync(HttpContext context, Exception exception) { if (exception == null) return; await WriteExceptionAsync(context, exception).ConfigureAwait(false); } private static async Task WriteExceptionAsync(HttpContext context, Exception exception) { //記錄日誌 LogHelper.Error(exception.GetBaseException().ToString()); //返回友好的提示 var response = context.Response; //狀態碼 if (exception is UnauthorizedAccessException) response.StatusCode = (int)HttpStatusCode.Unauthorized; else if (exception is Exception) response.StatusCode = (int)HttpStatusCode.BadRequest; response.ContentType = context.Request.Headers["Accept"]; if (response.ContentType.ToLower() == "application/xml") { await response.WriteAsync(Object2XmlString(ResultMsg.Failure(exception.GetBaseException().Message))).ConfigureAwait(false); } else { response.ContentType = "application/json"; await response.WriteAsync(JsonConvert.SerializeObject(ResultMsg.Failure(exception.GetBaseException().Message))).ConfigureAwait(false); } } /// <summary> /// 對象轉爲Xml /// </summary> /// <param name="o"></param> /// <returns></returns> private static string Object2XmlString(object o) { StringWriter sw = new StringWriter(); try { XmlSerializer serializer = new XmlSerializer(o.GetType()); serializer.Serialize(sw, o); } catch { //Handle Exception Code } finally { sw.Dispose(); } return sw.ToString(); } } }
返回值默認格式化成自定義類ResultMsg,可根據本身的項目需求,返回自定義實體async
同時會根據客戶端須要的格式,自動轉換爲xml或者jsonui
二、configure註冊this
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); //配置NLog loggerFactory.AddNLog(); env.ConfigureNLog("nlog.config"); app.UseApplicationInsightsRequestTelemetry(); app.UseApplicationInsightsExceptionTelemetry(); //異常處理中間件 app.UseMiddleware(typeof(ExceptionHandlerMiddleWare)); app.UseMvc(); ; }
三、收工,全部異常都可以處理了spa