@@ -1,13 +1,16 @@
|
||||
using IRaCIS.Core.Domain.Share;
|
||||
using IRaCIS.Core.Application.Helper.OtherTool;
|
||||
using IRaCIS.Core.Domain.Share;
|
||||
using IRaCIS.Core.Infrastructure;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace IRaCIS.Core.Application.Filter;
|
||||
|
||||
public class ProjectExceptionFilter(ILogger<ProjectExceptionFilter> _logger, IStringLocalizer _localizer) : Attribute, IExceptionFilter
|
||||
public class ProjectExceptionFilter(ILogger<ProjectExceptionFilter> _logger, IStringLocalizer _localizer, IConfiguration _config, IUserInfo _userInfo) : Attribute, IExceptionFilter
|
||||
{
|
||||
|
||||
public void OnException(ExceptionContext context)
|
||||
@@ -48,6 +51,29 @@ public class ProjectExceptionFilter(ILogger<ProjectExceptionFilter> _logger, ISt
|
||||
context.Result = new JsonResult(ResponseOutput.NotOk(_localizer["Project_ExceptionContactDeveloper"] + (exception.InnerException is null ? (exception.Message)
|
||||
: (exception.Message + "Inner ExceptionMsg:" + exception.InnerException?.Message)), ApiResponseCodeEnum.ProgramException));
|
||||
|
||||
try
|
||||
{
|
||||
string webhook = _config["WeComNoticeConfig:WebhookUrl"] ?? string.Empty;
|
||||
var uri = new Uri(_config["SystemEmailSendConfig:SiteUrl"]);
|
||||
var baseUrl = uri.GetLeftPart(UriPartial.Authority);
|
||||
|
||||
var userList = _config.GetSection("WeComNoticeConfig:NoticeUserList").Get<string[]>();
|
||||
|
||||
|
||||
|
||||
var requestBody = context.HttpContext.Items["RequestBody"] as string;
|
||||
|
||||
|
||||
|
||||
|
||||
WeComNotifier.SendErrorAsync(webhook, baseUrl, $"{_userInfo.UserName}({_userInfo.UserTypeShortName})", context.HttpContext.Request.Path, requestBody, exception, userList).GetAwaiter().GetResult();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
_logger.LogError($"异常过滤器里发送企业微信出现错误:{ex.Message}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
context.ExceptionHandled = true;//标记当前异常已经被处理过了
|
||||
@@ -58,6 +84,7 @@ public class ProjectExceptionFilter(ILogger<ProjectExceptionFilter> _logger, ISt
|
||||
|
||||
_logger.LogError(errorInfo);
|
||||
|
||||
|
||||
//_logger.LogError(exception, exception.Message);
|
||||
}
|
||||
else
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json;
|
||||
using RestSharp;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using IdentityModel;
|
||||
|
||||
namespace IRaCIS.Core.Application.Helper.OtherTool;
|
||||
|
||||
|
||||
|
||||
public static class WeComNotifier
|
||||
{
|
||||
|
||||
public static async Task SendErrorAsync(string webhook, string env, string userName,string api,string json, Exception ex, params string[] atUsers)
|
||||
{
|
||||
try
|
||||
{
|
||||
var client = new RestClient();
|
||||
var request = new RestRequest(webhook, Method.Post);
|
||||
|
||||
string hostName = Dns.GetHostName();
|
||||
string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
var stack = ex.StackTrace ?? "无堆栈信息";
|
||||
stack = stack.Replace("\n", "\n> "); // 每行变成引用,防止markdown断裂
|
||||
if (stack.Length > 1000)
|
||||
stack = stack.Substring(0, 1000) + "...(已截断)";
|
||||
|
||||
string atText = "";
|
||||
if (atUsers != null && atUsers.Any())
|
||||
{
|
||||
foreach (var u in atUsers)
|
||||
{
|
||||
atText += $" <@{u}>"; // 注意空格分隔
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//> **运行环境:** < font color = ""comment"" >{ EnvironmentName}</ font > danger danger warning
|
||||
var markdown = $@"## 🚨 系统异常告警
|
||||
> {atText}
|
||||
> **部署环境:** [{env}]({env})
|
||||
> **服务器:** {hostName}
|
||||
> **发生时间:** {time}
|
||||
> **操作人:** {userName}
|
||||
> **接口地址:** {api}
|
||||
### ❗ 异常信息
|
||||
<font color=""warning"">{ex.Message}</font>
|
||||
>**📦 请求数据(JSON 格式):**
|
||||
```json
|
||||
{json}
|
||||
```
|
||||
### 堆栈信息(部分)
|
||||
> <font color=""comment"">{stack}</font>
|
||||
";
|
||||
|
||||
var payload = new
|
||||
{
|
||||
msgtype = "markdown",
|
||||
markdown = new
|
||||
{
|
||||
content = markdown
|
||||
}
|
||||
};
|
||||
|
||||
request.AddHeader("Content-Type", "application/json");
|
||||
request.AddStringBody(JsonConvert.SerializeObject(payload), DataFormat.Json);
|
||||
|
||||
var response = await client.ExecuteAsync(request);
|
||||
|
||||
if (!response.IsSuccessful)
|
||||
{
|
||||
Log.Logger.Error($"企业微信通知失败: {response.StatusCode} {response.ErrorMessage}");
|
||||
}
|
||||
}
|
||||
catch (Exception notifyEx)
|
||||
{
|
||||
Log.Logger.Error("发送企业微信告警异常: " + notifyEx.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ using IRaCIS.Application.Contracts;
|
||||
using IRaCIS.Core.Application.BusinessFilter;
|
||||
using IRaCIS.Core.Application.Contracts;
|
||||
using IRaCIS.Core.Application.Helper;
|
||||
using IRaCIS.Core.Application.Helper.OtherTool;
|
||||
using IRaCIS.Core.Application.Service.BusinessFilter;
|
||||
using IRaCIS.Core.Application.ViewModel;
|
||||
using IRaCIS.Core.Domain;
|
||||
@@ -109,10 +110,13 @@ namespace IRaCIS.Core.Application.Service
|
||||
|
||||
//创建一个模型验证的方法
|
||||
[AllowAnonymous]
|
||||
[HttpPost]
|
||||
[HttpPost("{email}")]
|
||||
public async Task<IResponseOutput> PostModelVerify(ModelVerifyCommand modelVerify)
|
||||
{
|
||||
var webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=cdd97aab-d256-4f07-9145-a0a2b1555322";
|
||||
//await WeComNotifier.SendErrorAsync(webhook, "http://irc.test.extimaging.com/login", new Exception("测试异常"), new[] { "ZhouHang" });
|
||||
|
||||
throw new Exception("手动测试异常抛出");
|
||||
return ResponseOutput.Ok(modelVerify);
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user