Files
WMS-Api/src/WMS.Web.Repositories/DependencyInjection/ErrorHandlingMiddleware.cs
2023-10-18 10:56:19 +08:00

86 lines
3.3 KiB
C#

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace WMS.Web.Repositories.DependencyInjection
{
/// <summary>
/// 统一全局错误拦截
/// </summary>
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate next;
private readonly ILogger<ErrorHandlingMiddleware> _logger;
/// <summary>
/// 统一错误处理中间件
/// </summary>
public ErrorHandlingMiddleware(RequestDelegate next, ILogger<ErrorHandlingMiddleware> logger)
{
this.next = next;
_logger = logger;
}
private string bodyStr = "";
/// <summary>
/// 激活
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task Invoke(HttpContext context)
{
try
{
//默认 请求body只能读取一次 所以在这里需要手动把他设置成读取多次 并且 不能使用using 释放
context.Request.EnableBuffering();
StreamReader requestReader = new StreamReader(context.Request.Body, Encoding.UTF8);
bodyStr = await requestReader.ReadToEndAsync();
context.Request.Body.Seek(0, SeekOrigin.Begin);
await next(context);
}
catch (Exception ex)
{
// var statusCode = context.Response.StatusCode;
var statusCode = 500;
if (ex is ArgumentException) statusCode = 200;
_logger.LogError($"统一拦截异常处理: {ex.Message}, StackTrace:{ex.StackTrace},Path:{context.Request.Path},Parame:{bodyStr}");
await HandleExceptionAsync(context, statusCode, "服务器错误,不能执行此请求,请稍后重试,若问题一直存在,请与站点管理员联系");
// await HandleExceptionAsync(context, statusCode, "服务器错误");
}
finally
{
var statusCode = context.Response.StatusCode;
var msg = "";
// if (statusCode == 401)
// {
// msg = "未授权";
// }
if (statusCode == 404)
msg = "服务器暂无响应,请稍后重试,若问题一直存在,请与站点管理员联系";
else if (statusCode == 502) msg = "网关出错,请与站点管理员联系";
// else if (statusCode != 200)
// {
// msg = "未知错误";
// }
if (!string.IsNullOrWhiteSpace(msg)) await HandleExceptionAsync(context, statusCode, msg);
}
}
private static Task HandleExceptionAsync(HttpContext context, int statusCode, string msg)
{
string data = null;
var result = JsonConvert.SerializeObject(new { status = statusCode, result = data, message = msg });
context.Response.StatusCode = statusCode;
context.Response.ContentType = "application/json;charset=utf-8";
return context.Response.WriteAsync(result);
}
}
}