64 lines
2.3 KiB
C#
64 lines
2.3 KiB
C#
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
|
|
{
|
|
/// <summary>
|
|
/// 规范化异常处理
|
|
/// </summary>
|
|
/// <param name="app"></param>
|
|
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<IExceptionHandlerPathFeature>();
|
|
var error = FindFriendlyException(feature.Error);
|
|
httpContext.RequestServices.GetService<ILogger<Exception>>().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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 生成异常响应
|
|
/// </summary>
|
|
/// <param name="exception"></param>
|
|
/// <returns></returns>
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 递归查找友好异常
|
|
/// </summary>
|
|
/// <param name="exception"></param>
|
|
/// <returns></returns>
|
|
internal static Exception FindFriendlyException(Exception exception)
|
|
{
|
|
if (exception is FriendlyException || exception.InnerException is null)
|
|
return exception;
|
|
else return FindFriendlyException(exception.InnerException);
|
|
}
|
|
}
|
|
} |