Files
juipnet/Infrastructure/Hncore.Infrastructure/WebApi/Middleware/ErrorHandlingMiddleware.cs
wanyongkang d318014316 初始提交
2020-10-07 20:25:03 +08:00

103 lines
3.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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>();
}
}
}