Skip to content

Commit f354dd5

Browse files
committed
feat(api, cursor store): enhance error logging and improve user feedback during machine ID reset and account switching operations
1 parent b75ea43 commit f354dd5

5 files changed

Lines changed: 76 additions & 47 deletions

File tree

src-tauri/src/utils/logger.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ pub fn init_logger(config: LogConfig) -> Result<(), String> {
6060
let env_filter = EnvFilter::try_from_default_env()
6161
.unwrap_or_else(|_| EnvFilter::new(&log_level));
6262

63-
// 设置日志格式
63+
// 修改日志格式
6464
if config.json_format {
6565
// JSON格式
6666
let json_layer = fmt::layer()
@@ -72,8 +72,8 @@ pub fn init_logger(config: LogConfig) -> Result<(), String> {
7272
.with(env_filter)
7373
.with(json_layer);
7474

75-
// 如果启用控制台输出,添加控制台输出层
7675
if config.console_output {
76+
// 控制台输出可以保留颜色
7777
let console_layer = fmt::layer()
7878
.json()
7979
.with_timer(UtcTime::rfc_3339());
@@ -83,25 +83,27 @@ pub fn init_logger(config: LogConfig) -> Result<(), String> {
8383
subscriber.init();
8484
}
8585
} else {
86-
// 文本格式(类似loguru)
86+
// 文本格式 - 移除颜色相关配置
8787
let fmt_layer = fmt::layer()
8888
.with_target(true)
8989
.with_thread_ids(true)
9090
.with_level(true)
9191
.with_timer(UtcTime::rfc_3339())
92+
.with_ansi(false) // 禁用ANSI颜色
9293
.with_writer(file_appender);
9394

9495
let subscriber = tracing_subscriber::registry()
9596
.with(env_filter)
9697
.with(fmt_layer);
9798

98-
// 如果启用控制台输出,添加控制台输出层
9999
if config.console_output {
100+
// 控制台输出可以保留颜色
100101
let console_layer = fmt::layer()
101102
.with_target(true)
102103
.with_thread_ids(true)
103104
.with_level(true)
104-
.with_timer(UtcTime::rfc_3339());
105+
.with_timer(UtcTime::rfc_3339())
106+
.with_ansi(true);
105107

106108
subscriber.with(console_layer).init();
107109
} else {

src/api/index.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import type {
1212
Article,
1313
RegisterResponse
1414
} from './types'
15+
import Logger from '../utils/logger'
1516

1617
// 错误处理
1718
function handleApiResponse<T>(response: ApiResponse<T>): T {
@@ -172,6 +173,7 @@ export async function resetMachineId(params: { forceKill?: boolean, machineId?:
172173
machineId: params.machineId
173174
})
174175
} catch (error) {
176+
await Logger.error('重置机器码失败', { file: 'api/index.ts' })
175177
throw new ApiError(error instanceof Error ? error.message : '重置机器码失败')
176178
}
177179
}
@@ -180,11 +182,13 @@ export async function switchAccount(email: string, token: string, forceKill: boo
180182
try {
181183
const result = await invoke<boolean>('switch_account', { email, token, forceKill })
182184
if (result !== true) {
185+
await Logger.error(`切换账户失败: ${email}`, { file: 'api/index.ts' })
183186
throw new Error('切换账户失败')
184187
}
185188
} catch (error) {
189+
await Logger.error(`切换账户失败: ${email}, ${error}`, { file: 'api/index.ts' })
186190
const errorMsg = error instanceof Error ? error.message : '切换账户失败'
187-
if (errorMsg.includes('Cursor进程正在运行, 请先关闭Cursor')) {
191+
if (errorMsg.includes('Cursor进程正在运行')) {
188192
throw new Error('请先关闭 Cursor 或选择强制终止进程')
189193
}
190194
throw error
@@ -195,6 +199,7 @@ export async function getMachineIds(): Promise<MachineInfo> {
195199
try {
196200
return await invoke<MachineInfo>('get_machine_ids')
197201
} catch (error) {
202+
await Logger.error('获取机器码失败', { file: 'api/index.ts' })
198203
throw new ApiError(error instanceof Error ? error.message : '获取机器码失败')
199204
}
200205
}
@@ -203,6 +208,7 @@ export async function checkCursorRunning(): Promise<boolean> {
203208
try {
204209
return await invoke<boolean>('check_cursor_running')
205210
} catch (error) {
211+
await Logger.error('检查Cursor状态失败', { file: 'api/index.ts' })
206212
throw new ApiError(error instanceof Error ? error.message : '检查Cursor状态失败')
207213
}
208214
}
@@ -231,7 +237,7 @@ export async function applyHook(forceKill: boolean = false): Promise<void> {
231237
await invoke<void>('hook_main_js', { forceKill })
232238
} catch (error) {
233239
const errorMsg = error instanceof Error ? error.message : String(error)
234-
console.error('应用hook错误:', errorMsg)
240+
await Logger.error(`应用hook失败: ${errorMsg}`, { file: 'api/index.ts' })
235241

236242
if (errorMsg.includes('Cursor进程正在运行')) {
237243
throw new Error('请先关闭 Cursor 或选择强制终止进程')
@@ -255,7 +261,7 @@ export async function restoreHook(forceKill: boolean = false): Promise<void> {
255261
await invoke<void>('restore_hook', { forceKill })
256262
} catch (error) {
257263
const errorMsg = error instanceof Error ? error.message : String(error)
258-
console.error('恢复hook错误:', errorMsg)
264+
await Logger.error(`恢复hook失败: ${errorMsg}`, { file: 'api/index.ts' })
259265

260266
if (errorMsg.includes('Cursor进程正在运行')) {
261267
throw new Error('请先关闭 Cursor 或选择强制终止进程')

src/locales/messages.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ export const messages = {
160160
copyFailed: '复制失败',
161161
forceClose: '我已保存, 强制关闭',
162162
cursorRunning: 'Cursor 正在运行',
163-
cursorRunningMessage: '检测到 Cursor 正在运行, 请保存尚未更改的项目再继续操作!',
163+
cursorRunningMessage: '检测到 Cursor 正在运行, 请保存尚未更改的项目再继续操作! 不保存会导致Cursor报错! 报错了请别联系客服!',
164164
closingCursor: '正在关闭 Cursor...',
165165
forgotPassword: '忘记密码?',
166166
unknown: '未知',

src/stores/cursor.ts

Lines changed: 45 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import type { UsageInfo, MachineInfo } from '@/api/types'
1919
import type { HistoryAccount } from '@/types/history'
2020
import { useHistoryStore } from './history'
2121
import { open } from '@tauri-apps/plugin-dialog'
22+
import Logger from '../utils/logger'
2223

2324
export const useCursorStore = defineStore('cursor', () => {
2425
// 状态
@@ -148,20 +149,21 @@ export const useCursorStore = defineStore('cursor', () => {
148149
/**
149150
* 重置机器码
150151
*/
151-
async function resetMachine(params: { forceKill?: boolean, machineId?: string } = {}) {
152+
async function resetMachine({ forceKill = false, machineId }: { forceKill?: boolean; machineId?: string } = {}) {
152153
try {
153154
machineCodeLoading.value = true
154-
isLoading.value = true
155+
await Logger.info('开始重置机器码')
155156

156157
// 检查 Cursor 是否在运行
157-
if (!params.forceKill) {
158+
if (!forceKill) {
158159
const isRunning = await checkCursorRunning()
159160
if (isRunning) {
160161
throw new Error('Cursor进程正在运行, 请先关闭Cursor')
161162
}
162163
}
163164

164-
await resetMachineId(params)
165+
await resetMachineId({ forceKill, machineId })
166+
await Logger.info('机器码重置成功')
165167

166168
// 添加历史记录
167169
await saveHistoryRecord({
@@ -177,7 +179,7 @@ export const useCursorStore = defineStore('cursor', () => {
177179
await fetchCursorUsage()
178180
return true
179181
} catch (error) {
180-
console.error('重置机器码失败:', error)
182+
await Logger.error(`重置机器码失败: ${error}`)
181183
throw error
182184
} finally {
183185
isLoading.value = false
@@ -191,7 +193,7 @@ export const useCursorStore = defineStore('cursor', () => {
191193
async function switchCursorAccount(email?: string, token?: string, forceKill: boolean = false) {
192194
try {
193195
accountSwitchLoading.value = true
194-
isLoading.value = true
196+
await Logger.info('开始切换账户操作')
195197

196198
// 检查 Cursor 是否在运行
197199
if (!forceKill) {
@@ -203,15 +205,27 @@ export const useCursorStore = defineStore('cursor', () => {
203205

204206
// 如果未提供邮箱和token,则自动获取
205207
if (!email || !token) {
206-
const accountInfo = await getAccount(undefined, '1')
207-
if (!accountInfo.account_info.account || !accountInfo.account_info.token) {
208-
throw new Error('无法获取账户信息')
208+
try {
209+
const accountInfo = await getAccount(undefined, '1')
210+
if (!accountInfo.account_info.account || !accountInfo.account_info.token) {
211+
await Logger.error('获取账户信息失败,无法进行切换')
212+
throw new Error('获取账户信息失败')
213+
}
214+
email = accountInfo.account_info.account
215+
token = accountInfo.account_info.token
216+
} catch (error) {
217+
await Logger.error('获取新账户失败')
218+
throw error
209219
}
210-
email = accountInfo.account_info.account
211-
token = accountInfo.account_info.token
212220
}
213221

214-
await switchAccount(email, token, forceKill)
222+
try {
223+
await switchAccount(email, token, forceKill)
224+
await Logger.info(`账户切换成功: ${email}`)
225+
} catch (error) {
226+
await Logger.error(`账户切换失败: ${error}`)
227+
throw error
228+
}
215229

216230
// 添加历史记录
217231
await saveHistoryRecord({
@@ -227,7 +241,6 @@ export const useCursorStore = defineStore('cursor', () => {
227241
await fetchCursorUsage()
228242
return true
229243
} catch (error) {
230-
console.error('切换账户失败:', error)
231244
throw error
232245
} finally {
233246
isLoading.value = false
@@ -241,7 +254,7 @@ export const useCursorStore = defineStore('cursor', () => {
241254
async function quickChange(email?: string, token?: string, forceKill: boolean = false) {
242255
try {
243256
quickChangeLoading.value = true
244-
isLoading.value = true
257+
await Logger.info('开始一键换号操作')
245258

246259
// 检查 Cursor 是否在运行
247260
if (!forceKill) {
@@ -251,27 +264,22 @@ export const useCursorStore = defineStore('cursor', () => {
251264
}
252265
}
253266

254-
// 如果未提供邮箱和token,则自动获取
255-
if (!email || !token) {
256-
const accountInfo = await getAccount(undefined, '1')
257-
if (!accountInfo.account_info.account || !accountInfo.account_info.token) {
258-
throw new Error('无法获取账户信息')
259-
}
260-
email = accountInfo.account_info.account
261-
token = accountInfo.account_info.token
262-
}
263-
264267
// 先重置机器码
265268
try {
266-
await resetMachineId({ forceKill })
269+
await resetMachine({ forceKill })
267270
} catch (error) {
268-
console.error('重置机器码失败:', error)
269-
// 确保在机器码重置失败时立即终止,不执行账户切换
270-
throw new Error(`重置机器码失败,已终止账户切换操作: ${error instanceof Error ? error.message : String(error)}`)
271+
await Logger.error('一键换号时重置机器码失败')
272+
throw error
271273
}
272274

273-
// 只有在机器码重置成功后才执行账户切换
274-
await switchAccount(email, token, forceKill)
275+
// 再切换账户
276+
try {
277+
await switchCursorAccount(email, token, forceKill)
278+
await Logger.info('一键换号完成')
279+
} catch (error) {
280+
await Logger.error('一键换号时切换账户失败')
281+
throw error
282+
}
275283

276284
// 添加历史记录
277285
await saveHistoryRecord({
@@ -288,7 +296,6 @@ export const useCursorStore = defineStore('cursor', () => {
288296

289297
return true
290298
} catch (error) {
291-
console.error('一键更换失败:', error)
292299
throw error
293300
} finally {
294301
isLoading.value = false
@@ -330,6 +337,7 @@ export const useCursorStore = defineStore('cursor', () => {
330337
*/
331338
async function applyHookToClient(forceKill: boolean = false) {
332339
try {
340+
await Logger.info('开始注入Hook')
333341
operationLoading.value = true
334342
isLoading.value = true
335343

@@ -342,9 +350,11 @@ export const useCursorStore = defineStore('cursor', () => {
342350
// 触发检查以确保状态已更新
343351
await checkHook()
344352

353+
await Logger.info('Hook注入成功')
345354
return true
346355
} catch (error) {
347-
console.error('应用 Hook 失败:', error)
356+
await Logger.error(`Hook注入失败: ${error}`)
357+
hookStatus.value = false
348358
throw error
349359
} finally {
350360
isLoading.value = false
@@ -357,6 +367,7 @@ export const useCursorStore = defineStore('cursor', () => {
357367
*/
358368
async function restoreHookFromClient(forceKill: boolean = false) {
359369
try {
370+
await Logger.info('开始恢复Hook')
360371
operationLoading.value = true
361372
isLoading.value = true
362373

@@ -369,9 +380,10 @@ export const useCursorStore = defineStore('cursor', () => {
369380
// 触发检查以确保状态已更新
370381
await checkHook()
371382

383+
await Logger.info('Hook恢复成功')
372384
return true
373385
} catch (error) {
374-
console.error('恢复 Hook 失败:', error)
386+
await Logger.error(`Hook恢复失败: ${error}`)
375387
throw error
376388
} finally {
377389
isLoading.value = false

src/utils/logger.ts

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@ interface ErrorInfo {
77
stack?: string
88
}
99

10+
interface LogOptions {
11+
file?: string
12+
line?: number
13+
}
14+
1015
class Logger {
1116
private static formatError(error: Error | string): ErrorInfo {
1217
if (error instanceof Error) {
@@ -33,13 +38,13 @@ class Logger {
3338
}
3439
}
3540

36-
static async error(error: Error | string) {
41+
static async error(error: Error | string, options?: LogOptions) {
3742
const errorInfo = this.formatError(error)
3843
try {
3944
await invoke('log_error', {
4045
message: errorInfo.message,
41-
file: errorInfo.file,
42-
line: errorInfo.line
46+
file: options?.file || errorInfo.file,
47+
line: options?.line || errorInfo.line
4348
})
4449

4550
// 如果有堆栈信息,额外记录
@@ -53,9 +58,13 @@ class Logger {
5358
}
5459
}
5560

56-
static async warn(message: string, file?: string, line?: number) {
61+
static async warn(message: string, options?: LogOptions) {
5762
try {
58-
await invoke('log_warn', { message, file, line })
63+
await invoke('log_warn', {
64+
message,
65+
file: options?.file,
66+
line: options?.line
67+
})
5968
} catch (e) {
6069
console.error('Failed to log warning:', e)
6170
}

0 commit comments

Comments
 (0)