Files
juipnet/Infrastructure/Hncore.Infrastructure/WebApi/Middleware/ErrorHandlingMiddleware.cs

103 lines
2.9 KiB
C#
Raw Normal View History

2024-04-10 13:55:27 +08:00
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.Data;
using Hncore.Infrastructure.Extension;
using Hncore.Infrastructure.OpenApi;
using Hncore.Infrastructure.Serializer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Hncore.Infrastructure.Core.Web;
namespace Hncore.Infrastructure.WebApi
{
/// <summary>
/// 统一错误异常处理中间件类
/// </summary>
///
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (Exception ex)
{
string requestMsg = "请求URL" + context.Request.GetAbsoluteUri() + "";
requestMsg += "\nMethod" + context.Request.Method + "\n";
if (context.Request.Method.ToLower() != "get")
{
var requestBody = await context.Request.ReadBodyAsStringAsync();
requestMsg += "Body\n" + requestBody +
"\n------------------------\n";
}
else
{
requestMsg += "\n------------------------\n";
}
await HandleExceptionAsync(context, ex, requestMsg);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception ex,
string requestMsg)
{
ResultCode code = ResultCode.C_UNKNOWN_ERROR;
string msg = "";
if (ex is BusinessException bex)
{
code = bex.Code;
msg = bex.Message;
LogHelper.Error($"业务异常,{msg}", requestMsg + ex);
}
else
{
if (EnvironmentVariableHelper.IsAspNetCoreProduction)
{
msg = "系统繁忙,请稍后再试";
}
else
{
msg = ex.Message;
}
LogHelper.Error($"未知异常,{ex.Message}", requestMsg + ex);
}
var data = new ApiResult(code, msg);
var result = data.ToJson();
context.Response.ContentType = "application/json;charset=utf-8";
return context.Response.WriteAsync(result);
}
}
public static class ErrorHandlingExtensions
{
public static IApplicationBuilder UseErrorHandling(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ErrorHandlingMiddleware>();
}
}
}