fix(config): 优雅处理 Provider 未配置错误
- 添加 ConfigurationError 类替代 process.exit(1) - Server 端捕获配置错误并返回友好消息 - UI 端支持 config_error 类型的 WebSocket 消息 - 服务器不再因配置缺失而崩溃
This commit is contained in:
@@ -4,6 +4,23 @@ import * as os from 'os';
|
||||
import type { AgentConfig, ProviderType } from '../types/index.js';
|
||||
import { providerRegistry, resolveApiKey } from '../provider/index.js';
|
||||
|
||||
/**
|
||||
* 配置错误异常
|
||||
*
|
||||
* 当配置缺失或无效时抛出,用于替代 process.exit()
|
||||
* 允许调用方优雅地处理错误并向用户显示友好提示
|
||||
*/
|
||||
export class ConfigurationError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly provider: string,
|
||||
public readonly missingKey: 'apiKey' | 'provider'
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'ConfigurationError';
|
||||
}
|
||||
}
|
||||
|
||||
const CONFIG_DIR = path.join(os.homedir(), '.ai-terminal-assistant');
|
||||
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
|
||||
|
||||
@@ -90,9 +107,11 @@ export function loadConfig(): AgentConfig {
|
||||
const finalApiKey = resolveApiKey(providerConfig);
|
||||
|
||||
if (!finalApiKey) {
|
||||
console.error(`❌ 错误: 未配置 API Key`);
|
||||
console.error(`请在设置中配置 ${finalProvider} 的 API Key`);
|
||||
process.exit(1);
|
||||
throw new ConfigurationError(
|
||||
`未配置 ${finalProvider} 的 API Key,请在 Provider 设置中配置`,
|
||||
finalProvider,
|
||||
'apiKey'
|
||||
);
|
||||
}
|
||||
|
||||
// 确定模型
|
||||
|
||||
Reference in New Issue
Block a user