Skip to content

Commit 565d011

Browse files
committed
优化 ChatGPTTranslator的错误处理和参数校验
1 parent d66f690 commit 565d011

File tree

1 file changed

+79
-53
lines changed

1 file changed

+79
-53
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using Mikoto.Helpers.Network;
22
using Mikoto.Translators.Interfaces;
33
using System.Net.Http;
4+
using System.Text;
45
using System.Text.Json;
56
using System.Windows;
67

@@ -17,102 +18,126 @@ private ChatGPTTranslator() { }
1718
public static readonly string SIGN_UP_URL = "https://platform.openai.com";
1819
public static readonly string BILL_URL = "https://platform.openai.com/account/usage";
1920
public static readonly string DOCUMENT_URL = "https://platform.openai.com/docs/introduction/overview";
20-
21+
2122
private string? openai_model = "gpt-3.5-turbo";
22-
private string? apiKey; //ChatGPT翻译API的密钥
23-
private string? apiUrl; //ChatGPT翻译API的URL
24-
private string errorInfo = string.Empty; //错误信息
23+
private string? apiKey; // ChatGPT 翻译 API 的密钥
24+
private string? apiUrl; // ChatGPT 翻译 API 的 URL
25+
private string lastErrorMessage = string.Empty;
2526

26-
public string TranslatorDisplayName { get { return Application.Current.Resources["ChatGPTTranslator"].ToString()!; } }
27+
public string TranslatorDisplayName => Application.Current.Resources["ChatGPTTranslator"]?.ToString() ?? "ChatGPT Translator";
2728

2829
public string GetLastError()
2930
{
30-
return errorInfo;
31+
return lastErrorMessage;
3132
}
3233

3334
public async Task<string?> TranslateAsync(string sourceText, string desLang, string srcLang)
3435
{
35-
string q = sourceText;
36-
37-
if (sourceText == "" || desLang == "" || srcLang == "")
36+
// 参数校验
37+
if (string.IsNullOrWhiteSpace(sourceText) || string.IsNullOrWhiteSpace(desLang) || string.IsNullOrWhiteSpace(srcLang))
3838
{
39-
errorInfo = "Param Missing";
39+
SetError("Missing required parameters.");
4040
return null;
4141
}
42-
string retString;
43-
string jsonParam = $"{{\"model\": \"{openai_model}\",\"messages\": [{{\"role\": \"system\", \"content\": \"Translate {srcLang} To {desLang}\"}},{{\"role\": \"user\", \"content\": \"{q}\"}}]}}";
42+
43+
var requestPayload = new
44+
{
45+
model = openai_model,
46+
messages = new[]
47+
{
48+
new { role = "system", content = $"Translate {srcLang} To {desLang}" },
49+
new { role = "user", content = sourceText }
50+
}
51+
};
52+
53+
string jsonParam = JsonSerializer.Serialize(requestPayload, TranslatorCommon.JsonSerializerOptions);
4454
var hc = CommonHttpClient.Instance;
45-
var req = new StringContent(jsonParam, null, "application/json");
55+
var req = new StringContent(jsonParam, Encoding.UTF8, "application/json");
4656
hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
57+
4758
try
4859
{
49-
HttpResponseMessage? httpResponseMessage = await hc.PostAsync(apiUrl, req);
50-
retString = await httpResponseMessage.Content.ReadAsStringAsync();
60+
using HttpResponseMessage httpResponseMessage = await hc.PostAsync(apiUrl, req);
61+
62+
// 检查 HTTP 状态码
63+
if (!httpResponseMessage.IsSuccessStatusCode)
64+
{
65+
string errorContent = await httpResponseMessage.Content.ReadAsStringAsync();
66+
HandleApiError(errorContent);
67+
return null;
68+
}
69+
70+
string responseString = await httpResponseMessage.Content.ReadAsStringAsync();
71+
72+
// 解析 API 响应
73+
if (JsonSerializer.Deserialize<ChatResponse>(responseString, TranslatorCommon.JsonSerializerOptions) is { } oinfo)
74+
{
75+
return oinfo.choices.FirstOrDefault().message.content ?? HandleUnknownError(responseString);
76+
}
77+
78+
return HandleUnknownError(responseString);
5179
}
5280
catch (HttpRequestException ex)
5381
{
54-
errorInfo = ex.Message;
82+
SetError($"Network error: {ex.Message}");
5583
return null;
5684
}
5785
catch (TaskCanceledException ex)
5886
{
59-
errorInfo = ex.Message;
87+
SetError($"Request timeout: {ex.Message}");
6088
return null;
6189
}
62-
finally
63-
{
64-
req.Dispose();
65-
}
66-
67-
ChatResponse oinfo;
68-
69-
try
90+
catch (Exception ex)
7091
{
71-
oinfo = JsonSerializer.Deserialize<ChatResponse>(retString, TranslatorCommon.JsonSerializerOptions);
72-
}
73-
catch
74-
{
75-
errorInfo = "JsonConvert Error";
92+
SetError($"Unexpected error: {ex.Message}");
7693
return null;
7794
}
78-
79-
try
80-
{
81-
return oinfo.choices[0].message.content;
82-
}
83-
catch
84-
{
85-
try
86-
{
87-
var err = JsonSerializer.Deserialize<ChatResErr>(retString, TranslatorCommon.JsonSerializerOptions);
88-
errorInfo = err.error.message;
89-
return null;
90-
}
91-
catch
92-
{
93-
errorInfo = "Unknown error";
94-
return null;
95-
}
96-
}
9795
}
9896

9997
public static ITranslator TranslatorInit(params string[] param)
10098
{
10199
if (param.Length < 3)
102100
throw new ArgumentException("Expected 3 parameters: API Key, API URL, Model");
103101

104-
105-
ChatGPTTranslator chatGPTTranslator = new()
102+
return new ChatGPTTranslator
106103
{
107104
apiKey = param[0],
108105
apiUrl = param[1],
109106
openai_model = param[2],
110107
};
111-
return chatGPTTranslator;
108+
}
109+
110+
private void SetError(string message)
111+
{
112+
lastErrorMessage = message;
113+
}
114+
115+
private string? HandleUnknownError(string response)
116+
{
117+
SetError($"Unknown API response: {response}");
118+
return null;
119+
}
120+
121+
private void HandleApiError(string errorContent)
122+
{
123+
try
124+
{
125+
if (JsonSerializer.Deserialize<ChatResErr>(errorContent, TranslatorCommon.JsonSerializerOptions) is ChatResErr err && err.error.code != null)
126+
{
127+
SetError(err.error.message);
128+
}
129+
else
130+
{
131+
HandleUnknownError(errorContent);
132+
}
133+
}
134+
catch
135+
{
136+
HandleUnknownError(errorContent);
137+
}
112138
}
113139
}
114140

115-
#pragma warning disable 0649
116141
public struct ChatResponse
117142
{
118143
public string id;
@@ -156,3 +181,4 @@ public struct ChatError
156181
public object code;
157182
}
158183
}
184+

0 commit comments

Comments
 (0)