CSharp.Template/YuanXuan.IM.Api/Filters/GlobalExceptionCatchFilter.cs

136 lines
4.7 KiB
C#
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.Text.RegularExpressions;
using System.Text;
using Mapster;
using Masuit.Tools;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using YuanXuan.IM.Common.Response;
using YuanXuan.IM.Common.Exceptions;
namespace LearningOfficer.OA.Mobile.Api.Filters
{
/// <summary>
/// 全局异常捕获过滤器
/// </summary>
public class GlobalExceptionCatchFilter : IAsyncExceptionFilter
{
private readonly ILogger<GlobalExceptionCatchFilter> _logger;
public GlobalExceptionCatchFilter(ILogger<GlobalExceptionCatchFilter> logger)
{
_logger = logger; //在构造函数中注入日志处理实例
}
public async Task OnExceptionAsync(ExceptionContext context)
{
// 如果异常没有被处理则进行处理
if (context.ExceptionHandled == false)
{
// 定义返回类型
BaseResponse<object> result;
// 如果为业务逻辑抛出的内部异常
if (context.Exception is BusinessException ex)
{
if (ex.BussinessExceptionData != null)
{
result = new BaseResponse<object>((int)ex.ErrorCode, context.Exception.Message, ex.BussinessExceptionData);
//将result的data转换为Dictionary<string, object>
var data = result.data.ToDictionary();
ConvertKeysToCamelCase(data);
result.data = data;
}
else
{
result = new BaseResponse<object>((int)ex.ErrorCode, context.Exception.Message);
}
}
else
{
// 程序异常,不对外暴露程序异常细节
result = new BaseResponse<object>((int)BusinessExceptionCode.AppError, "服务器好像出错了!"
// ,new
//{
// RequestId = context.HttpContext.TraceIdentifier
//}
);
//使用日志对象 _logger 的 LogError() 方法将异常信息写入日志文件
_logger.LogError(context.Exception, context.Exception.Message);
}
context.Result = new ContentResult
{
// 返回状态码设置为200表示成功
StatusCode = StatusCodes.Status200OK,
// 设置返回格式
ContentType = "application/json;charset=utf-8",
Content = result.ToJsonString()
};
}
// 设置为true表示异常已经被处理了
context.ExceptionHandled = true;
}
public static void ConvertKeysToCamelCase(Dictionary<string, object> dictionary)
{
var keys = dictionary.Keys.ToList();
foreach (var key in keys)
{
string ItemKey = key;
if (ItemKey.Length >= 1 && char.IsUpper(ItemKey[0]))
{
ItemKey = char.ToLower(ItemKey[0]) + ItemKey.Substring(1);
}
var camelCaseKey = ChangeName(ItemKey);
if (dictionary.ContainsKey(camelCaseKey))
{
dictionary[camelCaseKey] = dictionary[key];
}
else
{
dictionary.Add(camelCaseKey, dictionary[key]);
}
dictionary.Remove(key);
}
}
/// <summary>
/// 将下划线命名转换为小驼峰命名
/// </summary>
/// <param name="name">变量名</param>
/// <returns></returns>
private static string ChangeName(string name)
{
Match mt = Regex.Match(name, @"_(\w*)*");
if (mt.Success)
{
var sb = new StringBuilder();
bool toUpper = false;
for (int i = 0; i < name.Length; i++)
{
char c = name[i];
if (c == '_')
{
toUpper = true;
}
else
{
sb.Append(toUpper ? char.ToUpperInvariant(c) : c);
toUpper = false;
}
}
if (sb.Length > 0)
sb[0] = char.ToLowerInvariant(sb[0]);
return sb.ToString();
}
return name;
}
}
}