初始提交
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
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>();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user