using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System.Net; namespace Syc.Abp.Application.Contracts { public static class SycAbpContractsExtensions { /// /// 规范化异常处理 /// /// public static void UseSpecificationException(this IApplicationBuilder app) { app.UseExceptionHandler(configure => { configure.Run(HandleExceptionAsync); }); } internal async static Task HandleExceptionAsync(HttpContext httpContext) { var feature = httpContext.Features.Get(); var error = FindFriendlyException(feature.Error); httpContext.RequestServices.GetService>().LogError(error, "An exception occurred: {exceptionMessage}"); var result = feature.Error.ExceptionConvertResponse(); httpContext.Response.ContentType = "application/json"; httpContext.Response.StatusCode = (int)HttpStatusCode.OK; await httpContext.Response.WriteAsJsonAsync(result); } /// /// 生成异常响应 /// /// /// internal static Response ExceptionConvertResponse(this Exception exception) { int errorCode = -1; exception = FindFriendlyException(exception); string message = exception.Message; if (exception is FriendlyException) errorCode = (exception as FriendlyException).Code; else errorCode = 500; return Response.Error(errorCode,message); } /// /// 递归查找友好异常 /// /// /// internal static Exception FindFriendlyException(Exception exception) { if (exception is FriendlyException || exception.InnerException is null) return exception; else return FindFriendlyException(exception.InnerException); } } }