Skip to content

Commit a114b8f

Browse files
committed
增加更多的API错误类型
优化API的错误判断 代码审查特性增加NeedReview 删除没什么用的代码审查程序
1 parent 034197a commit a114b8f

File tree

8 files changed

+179
-272
lines changed

8 files changed

+179
-272
lines changed

CodeReviewAnalysis/CodeReviewAnalysis.csproj

Lines changed: 0 additions & 12 deletions
This file was deleted.

CodeReviewAnalysis/Program.cs

Lines changed: 0 additions & 8 deletions
This file was deleted.

Sora.sln

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sora", "Sora\Sora.csproj",
77
EndProject
88
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sora_Test", "Sora_Test\Sora_Test.csproj", "{F0DFEC93-63EA-4514-A87E-FC21FD849A8B}"
99
EndProject
10-
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CodeReviewAnalysis", "CodeReviewAnalysis\CodeReviewAnalysis.csproj", "{4DF855B4-B371-4321-AD51-B2BC7DAEFFD2}"
11-
EndProject
1210
Global
1311
GlobalSection(SolutionConfigurationPlatforms) = preSolution
1412
Debug|Any CPU = Debug|Any CPU
@@ -23,10 +21,6 @@ Global
2321
{F0DFEC93-63EA-4514-A87E-FC21FD849A8B}.Debug|Any CPU.Build.0 = Debug|Any CPU
2422
{F0DFEC93-63EA-4514-A87E-FC21FD849A8B}.Release|Any CPU.ActiveCfg = Release|Any CPU
2523
{F0DFEC93-63EA-4514-A87E-FC21FD849A8B}.Release|Any CPU.Build.0 = Release|Any CPU
26-
{4DF855B4-B371-4321-AD51-B2BC7DAEFFD2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27-
{4DF855B4-B371-4321-AD51-B2BC7DAEFFD2}.Debug|Any CPU.Build.0 = Debug|Any CPU
28-
{4DF855B4-B371-4321-AD51-B2BC7DAEFFD2}.Release|Any CPU.ActiveCfg = Release|Any CPU
29-
{4DF855B4-B371-4321-AD51-B2BC7DAEFFD2}.Release|Any CPU.Build.0 = Release|Any CPU
3024
EndGlobalSection
3125
GlobalSection(SolutionProperties) = preSolution
3226
HideSolutionNode = FALSE

Sora/Attributes/CodeReview.cs

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,12 @@ public class Reviewed : Attribute
1111
/// <summary>
1212
/// 审核者
1313
/// </summary>
14-
public string Person { get; set; }
14+
public string Person { get; }
1515

1616
/// <summary>
1717
/// 时间
1818
/// </summary>
19-
public string Time { get; set; }
19+
public string Time { get; }
2020

2121
/// <summary>
2222
/// 表明您已经审核了该代码
@@ -29,4 +29,25 @@ public Reviewed(string person, string dt)
2929
Time = dt;
3030
}
3131
}
32+
33+
/// <summary>
34+
/// 需要审查特性类
35+
/// </summary>
36+
[AttributeUsage(AttributeTargets.Method)]
37+
public class NeedReview : Attribute
38+
{
39+
/// <summary>
40+
/// 修改的位置(行号或ALL)
41+
/// </summary>
42+
public string ModifiedLines { get; }
43+
44+
/// <summary>
45+
/// 表明您认为这段代码需要审查
46+
/// </summary>
47+
/// <param name="lines">修改行号/ALL</param>
48+
public NeedReview(string lines)
49+
{
50+
ModifiedLines = lines;
51+
}
52+
}
3253
}

Sora/Enumeration/ApiType/ApiStatusType.cs

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ public enum ApiStatusType
1818
/// </summary>
1919
Failed = 100,
2020

21+
/// <summary>
22+
/// 404
23+
/// </summary>
24+
Forbidden = 404,
25+
2126
/// <summary>
2227
/// 404
2328
/// </summary>
@@ -29,13 +34,28 @@ public enum ApiStatusType
2934
Error = 502,
3035

3136
/// <summary>
32-
/// API执行失败
37+
/// API超时
3338
/// </summary>
34-
Failed_ = 102,
39+
TimeOut = -1,
3540

3641
/// <summary>
37-
/// API超时
42+
/// API没有返回任何信息
43+
/// </summary>
44+
NullResponse = -2,
45+
46+
/// <summary>
47+
/// WS通信失败
48+
/// </summary>
49+
SocketSendError = -3,
50+
51+
/// <summary>
52+
/// 未知错误
53+
/// </summary>
54+
ObservableError = -4,
55+
56+
/// <summary>
57+
/// 未知状态
3858
/// </summary>
39-
TimeOut = -1
59+
UnknownStatus = -5
4060
}
4161
}

Sora/Helper.cs

Lines changed: 0 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
using System.Collections.Generic;
44
using System.Linq;
55
using System.Net.NetworkInformation;
6-
using System.Reflection;
76
using Sora.Attributes;
87
using Sora.Entities.Info.InternalDataInfo;
98
using YukariToolBox.Extensions;
@@ -57,56 +56,6 @@ internal static bool AddOrExist(this List<CommandInfo> list, CommandInfo data)
5756

5857
#endregion
5958

60-
#region 代码审计
61-
62-
/// <summary>
63-
/// <para>仅用于项目组内部的代码审查</para>
64-
/// <para>请不要使用此方法</para>
65-
/// </summary>
66-
public static void CheckReviewed()
67-
{
68-
var assembly = AppDomain.CurrentDomain.GetAssemblies()
69-
.Single(assem => assem.FullName == Assembly.GetExecutingAssembly().FullName);
70-
71-
var methods = new List<MemberInfo>();
72-
73-
assembly.GetTypes()
74-
.Where(type => type.IsClass)
75-
.Select(type => type.GetMethods())
76-
.ToList()
77-
.ForEach(array => methods.AddRange(array));
78-
79-
assembly.GetTypes()
80-
.Where(type => type.IsClass)
81-
.Select(type => type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance))
82-
.ToList()
83-
.ForEach(array => methods.AddRange(array));
84-
85-
assembly.GetTypes()
86-
.Where(type => type.IsClass)
87-
.Select(type => type.GetMethods(BindingFlags.NonPublic | BindingFlags.Static))
88-
.ToList()
89-
.ForEach(array => methods.AddRange(array));
90-
91-
92-
var totalMethod = methods.Count;
93-
94-
var checkedMethod = methods.Where(m => m.IsDefined(typeof(Reviewed), false))
95-
.ToDictionary(m => m, m => m.GetCustomAttribute<Reviewed>());
96-
97-
var uncheckedMethod = methods.Where(m => !m.IsDefined(typeof(Reviewed), false))
98-
.ToList();
99-
100-
Log.Debug("Total Method Count", totalMethod);
101-
102-
Log.Debug("Checked Method",
103-
$"{checkedMethod.Count}\n{string.Join("\n", checkedMethod.Select(m => $"{m.Key.ReflectedType?.FullName}.{m.Key.Name} checked by {m.Value?.Person} {m.Value?.Time}"))}");
104-
105-
Log.Debug("Unchecked Method Count", uncheckedMethod.Count);
106-
}
107-
108-
#endregion
109-
11059
#region 网络
11160

11261
/// <summary>

Sora/Net/ReactiveApiManager.cs

Lines changed: 81 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44
using System.Threading.Tasks;
55
using Newtonsoft.Json;
66
using Newtonsoft.Json.Linq;
7+
using Sora.Attributes;
78
using Sora.Entities;
9+
using Sora.Entities.Info;
10+
using Sora.Enumeration.ApiType;
811
using Sora.OnebotModel.ApiParams;
912
using YukariToolBox.Extensions;
1013
using YukariToolBox.FormatLog;
@@ -36,8 +39,9 @@ internal static void GetResponse(Guid echo, JObject response)
3639
/// <param name="connectionGuid">服务器连接标识符</param>
3740
/// <param name="timeout">覆盖原有超时,在不为空时有效</param>
3841
/// <returns>API返回</returns>
39-
internal static async ValueTask<JObject> SendApiRequest(ApiRequest apiRequest, Guid connectionGuid,
40-
TimeSpan? timeout = null)
42+
[NeedReview("L61-L99")]
43+
internal static async ValueTask<(ApiStatus, JObject)> SendApiRequest(ApiRequest apiRequest, Guid connectionGuid,
44+
TimeSpan? timeout = null)
4145
{
4246
TimeSpan currentTimeout;
4347
if (timeout is null)
@@ -54,29 +58,98 @@ internal static async ValueTask<JObject> SendApiRequest(ApiRequest apiRequest, G
5458
currentTimeout = (TimeSpan) timeout;
5559
}
5660

61+
//错误数据
62+
(bool isTimeout, Exception exception) err = (false, null);
5763
//向客户端发送请求数据
5864
var apiTask = StaticVariable.ApiSubject
5965
.Where(request => request.Item1 == apiRequest.Echo)
6066
.Select(request => request.Item2)
6167
.Take(1)
6268
.Timeout(currentTimeout)
63-
.Catch(Observable.Return(new JObject()))
6469
.ToTask()
6570
.RunCatch(e =>
6671
{
6772
Log.Error("Sora|ReactiveApiManager",
6873
$"ApiSubject Error {Log.ErrorLogBuilder(e)}");
74+
err.isTimeout = e is TimeoutException;
75+
err.exception = e;
6976
return new JObject();
7077
});
71-
if (!ConnectionManager.SendMessage(connectionGuid, JsonConvert.SerializeObject(apiRequest, Formatting.None))
72-
) return null;
78+
//发送消息
79+
if (!ConnectionManager
80+
.SendMessage(connectionGuid, JsonConvert.SerializeObject(apiRequest, Formatting.None)))
81+
//API消息发送失败
82+
return (SocketSendError(), null);
83+
7384
//等待客户端返回调用结果
7485
var response = await apiTask.ConfigureAwait(false);
75-
if (response != null && response.Count != 0) return response;
76-
Log.Error("Sora|ReactiveApiManager", "api time out");
77-
return null;
86+
//检查API返回
87+
if (response != null && response.Count != 0)
88+
{
89+
return (GetApiStatus(response), response);
90+
}
91+
92+
//空响应
93+
if (err.exception == null) return (NullResponse(), null);
94+
//观察者抛出异常
95+
if (err.isTimeout) Log.Error("Sora|ReactiveApiManager", "api time out");
96+
return err.isTimeout
97+
? (TimeOut(), null)
98+
: (ObservableError(Log.ErrorLogBuilder(err.exception)), null);
7899
}
79100

80101
#endregion
102+
103+
#region API状态处理
104+
105+
/// <summary>
106+
/// 获取API状态返回值
107+
/// 所有API回调请求都会返回状态值
108+
/// </summary>
109+
/// <param name="msg">消息JSON</param>
110+
[NeedReview("ALL")]
111+
private static ApiStatus GetApiStatus(JObject msg)
112+
=> new()
113+
{
114+
RetCode = Enum.TryParse<ApiStatusType>(msg["retcode"]?.ToString() ?? string.Empty, out var messageCode)
115+
? messageCode
116+
: ApiStatusType.UnknownStatus,
117+
ApiMessage = $"{msg["msg"]}({msg["wording"]})",
118+
ApiStatusStr = msg["status"]?.ToString() ?? "failed"
119+
};
120+
121+
private static ApiStatus TimeOut()
122+
=> new()
123+
{
124+
RetCode = ApiStatusType.TimeOut,
125+
ApiMessage = "api timeout",
126+
ApiStatusStr = "timeout"
127+
};
128+
129+
private static ApiStatus NullResponse()
130+
=> new()
131+
{
132+
RetCode = ApiStatusType.NullResponse,
133+
ApiMessage = "get null response from api",
134+
ApiStatusStr = "failed"
135+
};
136+
137+
private static ApiStatus SocketSendError()
138+
=> new()
139+
{
140+
RetCode = ApiStatusType.SocketSendError,
141+
ApiMessage = "cannot send message to api",
142+
ApiStatusStr = "failed"
143+
};
144+
145+
private static ApiStatus ObservableError(string errLog)
146+
=> new()
147+
{
148+
RetCode = ApiStatusType.ObservableError,
149+
ApiMessage = errLog,
150+
ApiStatusStr = "observable error"
151+
};
152+
153+
#endregion
81154
}
82155
}

0 commit comments

Comments
 (0)