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 { /// /// 全局异常捕获过滤器 /// public class GlobalExceptionCatchFilter : IAsyncExceptionFilter { private readonly ILogger _logger; public GlobalExceptionCatchFilter(ILogger logger) { _logger = logger; //在构造函数中注入日志处理实例 } public async Task OnExceptionAsync(ExceptionContext context) { // 如果异常没有被处理则进行处理 if (context.ExceptionHandled == false) { // 定义返回类型 BaseResponse result; // 如果为业务逻辑抛出的内部异常 if (context.Exception is BusinessException ex) { if (ex.BussinessExceptionData != null) { result = new BaseResponse((int)ex.ErrorCode, context.Exception.Message, ex.BussinessExceptionData); //将result的data转换为Dictionary var data = result.data.ToDictionary(); ConvertKeysToCamelCase(data); result.data = data; } else { result = new BaseResponse((int)ex.ErrorCode, context.Exception.Message); } } else { // 程序异常,不对外暴露程序异常细节 result = new BaseResponse((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 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); } } /// /// 将下划线命名转换为小驼峰命名 /// /// 变量名 /// 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; } } }