Compare commits
2 Commits
9a90f1258b
...
45ec0fd021
| Author | SHA1 | Date | |
|---|---|---|---|
| 45ec0fd021 | |||
| 49d7f2c37e |
62
src/main.ts
62
src/main.ts
@@ -1,22 +1,16 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import { naiveUi } from '@/common/naive-ui/components.ts'
|
||||
import { SystemServiceIntegration } from '@/services/SystemServiceIntegration'
|
||||
import { registerBuiltInApps } from '@/apps'
|
||||
import { systemBootstrapper } from '@/services/di/SystemBootstrapper'
|
||||
import { ServiceProvider } from '@/services/di/ServiceProvider'
|
||||
import { ServiceIds } from '@/services/di/ServiceRegistry'
|
||||
|
||||
import 'virtual:uno.css'
|
||||
import './css/basic.css'
|
||||
|
||||
import App from './ui/App.vue'
|
||||
|
||||
// 注册内置应用
|
||||
registerBuiltInApps()
|
||||
|
||||
// 初始化系统服务
|
||||
const systemService = new SystemServiceIntegration({
|
||||
debug: import.meta.env.DEV
|
||||
})
|
||||
|
||||
// 创建应用实例
|
||||
const app = createApp(App)
|
||||
|
||||
@@ -24,38 +18,58 @@ const app = createApp(App)
|
||||
app.use(createPinia())
|
||||
app.use(naiveUi)
|
||||
|
||||
// 提供系统服务给组件使用
|
||||
app.provide('systemService', systemService)
|
||||
// 全局错误处理
|
||||
app.config.errorHandler = (error, instance, info) => {
|
||||
console.error('Vue应用错误:', error, info)
|
||||
}
|
||||
|
||||
// 初始化系统服务然后挂载应用
|
||||
systemService
|
||||
.initialize()
|
||||
.then(() => {
|
||||
// 启动应用函数
|
||||
async function startApplication() {
|
||||
try {
|
||||
// 注册内置应用
|
||||
registerBuiltInApps()
|
||||
|
||||
console.log('正在启动桌面系统...')
|
||||
|
||||
// 使用系统启动器初始化依赖注入系统和所有服务
|
||||
const success = await systemBootstrapper.bootstrap({
|
||||
debug: import.meta.env.DEV,
|
||||
autoCleanup: true
|
||||
})
|
||||
|
||||
if (!success) {
|
||||
throw new Error('系统启动失败')
|
||||
}
|
||||
|
||||
// 获取系统服务并提供给Vue应用
|
||||
const systemService = ServiceProvider.getSystemService()
|
||||
app.provide('systemService', systemService)
|
||||
|
||||
// 挂载应用
|
||||
app.mount('#app')
|
||||
console.log('桌面系统启动完成')
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
} catch (error) {
|
||||
console.error('系统启动失败:', error)
|
||||
// 显示错误信息
|
||||
document.body.innerHTML = `
|
||||
<div style="display: flex; justify-content: center; align-items: center; height: 100vh; font-family: sans-serif;">
|
||||
<div style="text-align: center; color: #e74c3c;">
|
||||
<h1>系统启动失败</h1>
|
||||
<p>错误信息: ${error.message}</p>
|
||||
<p>错误信息: ${error instanceof Error ? error.message : '未知错误'}</p>
|
||||
<button onclick="location.reload()" style="padding: 10px 20px; margin-top: 20px; cursor: pointer;">
|
||||
重新加载
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
})
|
||||
|
||||
// 全局错误处理
|
||||
app.config.errorHandler = (error, instance, info) => {
|
||||
console.error('Vue应用错误:', error, info)
|
||||
}
|
||||
}
|
||||
|
||||
// 启动应用
|
||||
startApplication()
|
||||
|
||||
// 在页面卸载时清理系统服务
|
||||
window.addEventListener('beforeunload', () => {
|
||||
systemService.shutdown()
|
||||
systemBootstrapper.shutdown()
|
||||
})
|
||||
|
||||
@@ -101,14 +101,24 @@ export interface SandboxEvents {
|
||||
/**
|
||||
* 应用沙箱引擎类
|
||||
*/
|
||||
import { ServiceProvider, Inject } from './di/ServiceProvider'
|
||||
import type { IServiceContainer } from './di/IServiceContainer'
|
||||
|
||||
export class ApplicationSandboxEngine {
|
||||
// 服务容器
|
||||
private serviceContainer: IServiceContainer
|
||||
|
||||
private sandboxes = reactive(new Map<string, SandboxInstance>())
|
||||
private performanceData = reactive(new Map<string, SandboxPerformance[]>())
|
||||
private monitoringInterval: number | null = null
|
||||
|
||||
// 资源服务
|
||||
@Inject('resourceService')
|
||||
private resourceService: ResourceService
|
||||
|
||||
constructor(resourceService: ResourceService) {
|
||||
constructor(resourceService: ResourceService, serviceContainer: IServiceContainer) {
|
||||
this.resourceService = resourceService
|
||||
this.serviceContainer = serviceContainer
|
||||
this.startPerformanceMonitoring()
|
||||
}
|
||||
|
||||
|
||||
79
src/services/IErrorHandler.ts
Normal file
79
src/services/IErrorHandler.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* 全局错误处理器接口
|
||||
* 负责统一处理系统中的所有错误
|
||||
*/
|
||||
export interface IErrorHandler {
|
||||
/**
|
||||
* 处理应用错误
|
||||
* @param error 错误对象
|
||||
* @param context 错误上下文信息
|
||||
* @returns 是否成功处理了错误
|
||||
*/
|
||||
handleError(error: Error | any, context?: ErrorContext): boolean
|
||||
|
||||
/**
|
||||
* 处理未捕获的异常
|
||||
*/
|
||||
setupGlobalErrorHandlers(): void
|
||||
|
||||
/**
|
||||
* 获取最近的错误记录
|
||||
* @param limit 获取的最大数量
|
||||
*/
|
||||
getRecentErrors(limit?: number): ErrorRecord[]
|
||||
}
|
||||
|
||||
/**
|
||||
* 错误上下文信息
|
||||
*/
|
||||
export interface ErrorContext {
|
||||
/**
|
||||
* 错误来源组件或服务名称
|
||||
*/
|
||||
source?: string
|
||||
|
||||
/**
|
||||
* 错误发生的操作
|
||||
*/
|
||||
operation?: string
|
||||
|
||||
/**
|
||||
* 相关的应用ID
|
||||
*/
|
||||
appId?: string
|
||||
|
||||
/**
|
||||
* 其他自定义信息
|
||||
*/
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
/**
|
||||
* 错误记录
|
||||
*/
|
||||
export interface ErrorRecord {
|
||||
/**
|
||||
* 错误ID
|
||||
*/
|
||||
id: string
|
||||
|
||||
/**
|
||||
* 错误对象
|
||||
*/
|
||||
error: Error | any
|
||||
|
||||
/**
|
||||
* 错误上下文
|
||||
*/
|
||||
context?: ErrorContext
|
||||
|
||||
/**
|
||||
* 错误发生时间
|
||||
*/
|
||||
timestamp: Date
|
||||
|
||||
/**
|
||||
* 是否已处理
|
||||
*/
|
||||
handled: boolean
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
import { reactive, ref } from 'vue'
|
||||
import { EventBuilderImpl } from '@/events/impl/EventBuilderImpl'
|
||||
import type { IEventBuilder, IEventMap, WindowFormDataUpdateParams } from '@/events/IEventBuilder'
|
||||
import type { ResourceType } from './ResourceService'
|
||||
|
||||
// 导入所有服务
|
||||
import { WindowFormService } from './WindowFormService.ts'
|
||||
import { ResourceService } from './ResourceService'
|
||||
import { ResourceService, ResourceType } from './ResourceService'
|
||||
import { ServiceProvider, Inject } from './di/ServiceProvider'
|
||||
import type { IServiceContainer } from './di/IServiceContainer'
|
||||
import { ServiceIds } from './di/ServiceRegistry'
|
||||
import { WindowFormService } from './WindowFormService'
|
||||
import { ApplicationSandboxEngine } from './ApplicationSandboxEngine'
|
||||
import { ApplicationLifecycleManager } from './ApplicationLifecycleManager'
|
||||
import { externalAppDiscovery } from './ExternalAppDiscovery'
|
||||
@@ -55,12 +54,24 @@ export class SystemServiceIntegration {
|
||||
private config: SystemServiceConfig
|
||||
private startTime: Date
|
||||
|
||||
// 核心服务实例
|
||||
private eventBus: IEventBuilder<any>
|
||||
private windowFormService!: WindowFormService
|
||||
private resourceService!: ResourceService
|
||||
private sandboxEngine!: ApplicationSandboxEngine
|
||||
private lifecycleManager!: ApplicationLifecycleManager
|
||||
// 核心服务实例 - 使用依赖注入
|
||||
@Inject(ServiceIds.EVENT_BUILDER)
|
||||
private eventBus!: IEventBuilder<any>
|
||||
|
||||
@Inject(ServiceIds.WINDOW_FORM_SERVICE)
|
||||
private windowFormService!: any
|
||||
|
||||
@Inject(ServiceIds.RESOURCE_SERVICE)
|
||||
private resourceService!: any
|
||||
|
||||
@Inject(ServiceIds.SANDBOX_ENGINE)
|
||||
private sandboxEngine!: any
|
||||
|
||||
@Inject(ServiceIds.LIFECYCLE_MANAGER)
|
||||
private lifecycleManager!: any
|
||||
|
||||
@Inject(ServiceIds.EXTERNAL_APP_DISCOVERY)
|
||||
private externalAppDiscovery!: any
|
||||
|
||||
// 系统状态
|
||||
private systemStatus = reactive<SystemStatus>({
|
||||
@@ -78,8 +89,9 @@ export class SystemServiceIntegration {
|
||||
// 性能监控
|
||||
private cleanupInterval: number | null = null
|
||||
private performanceInterval: number | null = null
|
||||
private serviceContainer: IServiceContainer
|
||||
|
||||
constructor(config: SystemServiceConfig = {}) {
|
||||
constructor(serviceContainer: IServiceContainer, config: SystemServiceConfig = {}) {
|
||||
this.config = {
|
||||
debug: false,
|
||||
autoCleanup: true,
|
||||
@@ -88,7 +100,7 @@ export class SystemServiceIntegration {
|
||||
}
|
||||
|
||||
this.startTime = new Date()
|
||||
this.eventBus = new EventBuilderImpl<any>()
|
||||
this.serviceContainer = serviceContainer
|
||||
|
||||
this.setupGlobalErrorHandling()
|
||||
}
|
||||
@@ -98,36 +110,31 @@ export class SystemServiceIntegration {
|
||||
*/
|
||||
public async initialize(): Promise<void> {
|
||||
if (this.initialized.value) {
|
||||
throw new Error('系统服务已初始化')
|
||||
console.warn('系统服务已经初始化')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('开始初始化系统服务...')
|
||||
|
||||
// 按依赖顺序初始化服务
|
||||
await this.initializeServices()
|
||||
|
||||
// 设置服务间通信
|
||||
this.setupServiceCommunication()
|
||||
|
||||
// 设置SDK消息处理
|
||||
this.setupSDKMessageHandling()
|
||||
|
||||
// 启动自动清理
|
||||
// 启动自动清理(如果启用)
|
||||
if (this.config.autoCleanup) {
|
||||
this.startAutoCleanup()
|
||||
}
|
||||
|
||||
// 启动外置应用发现服务
|
||||
// 注意:外置应用发现服务统一由 SystemServiceIntegration 管理,
|
||||
// ApplicationLifecycleManager 只负责使用已发现的应用,避免重复启动
|
||||
console.log('启动外置应用发现服务...')
|
||||
await externalAppDiscovery.startDiscovery()
|
||||
|
||||
this.initialized.value = true
|
||||
this.running.value = true
|
||||
// 更新系统状态
|
||||
this.systemStatus.initialized = true
|
||||
this.systemStatus.running = true
|
||||
this.initialized.value = true
|
||||
this.running.value = true
|
||||
|
||||
// 标记所有服务状态为已启动
|
||||
this.systemStatus.servicesStatus = {
|
||||
windowFormService: true,
|
||||
resourceService: true,
|
||||
sandboxEngine: true,
|
||||
lifecycleManager: true
|
||||
}
|
||||
|
||||
console.log('系统服务初始化完成')
|
||||
} catch (error) {
|
||||
@@ -137,6 +144,8 @@ export class SystemServiceIntegration {
|
||||
}
|
||||
}
|
||||
|
||||
// ... 保留其他现有方法
|
||||
|
||||
/**
|
||||
* 获取系统状态
|
||||
*/
|
||||
|
||||
41
src/services/di/IServiceContainer.ts
Normal file
41
src/services/di/IServiceContainer.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* 服务容器接口
|
||||
* 负责管理和提供所有系统服务的实例
|
||||
*/
|
||||
export interface IServiceContainer {
|
||||
/**
|
||||
* 注册服务
|
||||
* @param id 服务唯一标识符
|
||||
* @param factory 服务工厂函数
|
||||
* @param dependencies 依赖的服务ID数组
|
||||
*/
|
||||
register<T>(id: string, factory: ServiceFactory<T>, dependencies?: string[]): void
|
||||
|
||||
/**
|
||||
* 获取服务实例
|
||||
* @param id 服务唯一标识符
|
||||
* @returns 服务实例
|
||||
* @throws 当服务未注册时抛出错误
|
||||
*/
|
||||
getService<T>(id: string): T
|
||||
|
||||
/**
|
||||
* 检查服务是否已注册
|
||||
* @param id 服务唯一标识符
|
||||
* @returns 是否已注册
|
||||
*/
|
||||
has(id: string): boolean
|
||||
|
||||
/**
|
||||
* 初始化所有服务
|
||||
* 按照依赖关系顺序初始化服务
|
||||
*/
|
||||
initialize(): void
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务工厂函数类型
|
||||
* @param container 服务容器实例
|
||||
* @returns 服务实例
|
||||
*/
|
||||
export type ServiceFactory<T> = (container: IServiceContainer) => T
|
||||
138
src/services/di/ServiceContainerImpl.ts
Normal file
138
src/services/di/ServiceContainerImpl.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import type { IServiceContainer, ServiceFactory } from './IServiceContainer'
|
||||
|
||||
/**
|
||||
* 服务注册信息接口
|
||||
*/
|
||||
interface ServiceRegistration<T> {
|
||||
factory: ServiceFactory<T>
|
||||
dependencies: string[]
|
||||
instance: T | null
|
||||
initialized: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务容器实现
|
||||
* 使用工厂模式和依赖注入模式管理服务实例
|
||||
*/
|
||||
export class ServiceContainerImpl implements IServiceContainer {
|
||||
private services = new Map<string, ServiceRegistration<any>>()
|
||||
private initializationStack: string[] = []
|
||||
private initialized = false
|
||||
|
||||
/**
|
||||
* 注册服务
|
||||
* @param id 服务唯一标识符
|
||||
* @param factory 服务工厂函数
|
||||
* @param dependencies 依赖的服务ID数组
|
||||
*/
|
||||
public register<T>(id: string, factory: ServiceFactory<T>, dependencies: string[] = []): void {
|
||||
if (this.initialized) {
|
||||
throw new Error(`无法在容器初始化后注册服务: ${id}`)
|
||||
}
|
||||
|
||||
this.services.set(id, {
|
||||
factory,
|
||||
dependencies,
|
||||
instance: null,
|
||||
initialized: false
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取服务实例
|
||||
* @param id 服务唯一标识符
|
||||
* @returns 服务实例
|
||||
* @throws 当服务未注册或发生循环依赖时抛出错误
|
||||
*/
|
||||
public getService<T>(id: string): T {
|
||||
const registration = this.services.get(id)
|
||||
|
||||
if (!registration) {
|
||||
throw new Error(`未注册的服务: ${id}`)
|
||||
}
|
||||
|
||||
// 检测循环依赖
|
||||
if (this.initializationStack.includes(id)) {
|
||||
throw new Error(`检测到循环依赖: ${this.initializationStack.join(' -> ')} -> ${id}`)
|
||||
}
|
||||
|
||||
// 如果服务实例尚未创建,则创建它
|
||||
if (!registration.instance) {
|
||||
this.initializationStack.push(id)
|
||||
|
||||
try {
|
||||
// 首先确保所有依赖都已初始化
|
||||
for (const dependencyId of registration.dependencies) {
|
||||
this.getService(dependencyId)
|
||||
}
|
||||
|
||||
// 创建服务实例
|
||||
registration.instance = registration.factory(this)
|
||||
registration.initialized = true
|
||||
} finally {
|
||||
this.initializationStack.pop()
|
||||
}
|
||||
}
|
||||
|
||||
return registration.instance
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查服务是否已注册
|
||||
* @param id 服务唯一标识符
|
||||
* @returns 是否已注册
|
||||
*/
|
||||
public has(id: string): boolean {
|
||||
return this.services.has(id)
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化所有服务
|
||||
* 按照依赖关系顺序初始化服务
|
||||
*/
|
||||
public initialize(): void {
|
||||
if (this.initialized) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
// 初始化所有服务(按依赖顺序)
|
||||
this.services.forEach((_, id) => {
|
||||
this.getService(id)
|
||||
})
|
||||
|
||||
this.initialized = true
|
||||
} catch (error) {
|
||||
console.error('服务容器初始化失败:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有已注册服务的ID列表
|
||||
* @returns 服务ID列表
|
||||
*/
|
||||
public getRegisteredServices(): string[] {
|
||||
return Array.from(this.services.keys())
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除服务实例(用于测试)
|
||||
* @param id 服务ID,如果不提供则清除所有服务
|
||||
*/
|
||||
public clear(id?: string): void {
|
||||
if (id) {
|
||||
const registration = this.services.get(id)
|
||||
if (registration) {
|
||||
registration.instance = null
|
||||
registration.initialized = false
|
||||
}
|
||||
} else {
|
||||
this.services.forEach((registration) => {
|
||||
registration.instance = null
|
||||
registration.initialized = false
|
||||
})
|
||||
this.initialized = false
|
||||
}
|
||||
}
|
||||
}
|
||||
141
src/services/di/ServiceProvider.ts
Normal file
141
src/services/di/ServiceProvider.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
import { ServiceRegistry, ServiceIds } from './ServiceRegistry'
|
||||
import type { IServiceContainer } from './IServiceContainer'
|
||||
|
||||
/**
|
||||
* 服务提供者
|
||||
* 提供静态方法访问所有系统服务
|
||||
*/
|
||||
export class ServiceProvider {
|
||||
private static container: IServiceContainer | null = null
|
||||
private static initialized = false
|
||||
|
||||
/**
|
||||
* 初始化服务提供者
|
||||
* 注册并初始化所有服务
|
||||
*/
|
||||
public static initialize(): void {
|
||||
if (this.initialized) {
|
||||
return
|
||||
}
|
||||
|
||||
const registry = ServiceRegistry.getInstance()
|
||||
registry.registerAllServices()
|
||||
|
||||
this.container = registry.getContainer()
|
||||
this.container.initialize()
|
||||
|
||||
this.initialized = true
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取服务实例
|
||||
* @param id 服务ID
|
||||
* @returns 服务实例
|
||||
*/
|
||||
public static getService<T>(id: string): T {
|
||||
if (!this.container) {
|
||||
throw new Error('服务提供者尚未初始化')
|
||||
}
|
||||
return this.container.getService<T>(id)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取资源服务
|
||||
*/
|
||||
public static getResourceService(): any {
|
||||
return this.getService(ServiceIds.RESOURCE_SERVICE)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取窗口表单服务
|
||||
*/
|
||||
public static getWindowFormService(): any {
|
||||
return this.getService(ServiceIds.WINDOW_FORM_SERVICE)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取沙箱引擎
|
||||
*/
|
||||
public static getSandboxEngine(): any {
|
||||
return this.getService(ServiceIds.SANDBOX_ENGINE)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取生命周期管理器
|
||||
*/
|
||||
public static getLifecycleManager(): any {
|
||||
return this.getService(ServiceIds.LIFECYCLE_MANAGER)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取系统服务
|
||||
*/
|
||||
public static getSystemService(): any {
|
||||
return this.getService(ServiceIds.SYSTEM_SERVICE)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取事件构建器
|
||||
*/
|
||||
public static getEventBuilder(): any {
|
||||
return this.getService(ServiceIds.EVENT_BUILDER)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取外部应用发现服务
|
||||
*/
|
||||
public static getExternalAppDiscovery(): any {
|
||||
return this.getService(ServiceIds.EXTERNAL_APP_DISCOVERY)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取错误处理服务
|
||||
*/
|
||||
public static getErrorHandler(): any {
|
||||
return this.getService(ServiceIds.ERROR_HANDLER)
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否已初始化
|
||||
*/
|
||||
public static isInitialized(): boolean {
|
||||
return this.initialized
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取服务容器(仅用于高级场景)
|
||||
*/
|
||||
public static getContainer(): IServiceContainer | null {
|
||||
return this.container
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建服务工厂函数
|
||||
* @param constructor 服务构造函数
|
||||
* @param dependencyIds 依赖的服务ID数组
|
||||
* @returns 服务工厂函数
|
||||
*/
|
||||
export function createServiceFactory<T>(
|
||||
constructor: new (...args: any[]) => T,
|
||||
dependencyIds: string[] = []
|
||||
): (container: IServiceContainer) => T {
|
||||
return (container: IServiceContainer) => {
|
||||
const dependencies = dependencyIds.map((id) => container.getService(id))
|
||||
return new constructor(...dependencies)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务装饰器,用于标记需要注入的服务
|
||||
*/
|
||||
export function Inject(serviceId: string): PropertyDecorator {
|
||||
return (target: Object, propertyKey: string | symbol) => {
|
||||
const descriptor = {
|
||||
get: () => {
|
||||
return ServiceProvider.getService(serviceId)
|
||||
}
|
||||
}
|
||||
Object.defineProperty(target, propertyKey, descriptor)
|
||||
}
|
||||
}
|
||||
194
src/services/di/ServiceRegistry.ts
Normal file
194
src/services/di/ServiceRegistry.ts
Normal file
@@ -0,0 +1,194 @@
|
||||
import type { IServiceContainer, ServiceFactory } from './IServiceContainer'
|
||||
import { ServiceContainerImpl } from './ServiceContainerImpl'
|
||||
|
||||
/**
|
||||
* 服务ID常量
|
||||
*/
|
||||
export enum ServiceIds {
|
||||
RESOURCE_SERVICE = 'resourceService',
|
||||
WINDOW_FORM_SERVICE = 'windowFormService',
|
||||
SANDBOX_ENGINE = 'sandboxEngine',
|
||||
LIFECYCLE_MANAGER = 'lifecycleManager',
|
||||
SYSTEM_SERVICE = 'systemService',
|
||||
EVENT_BUILDER = 'eventBuilder',
|
||||
EXTERNAL_APP_DISCOVERY = 'externalAppDiscovery',
|
||||
ERROR_HANDLER = 'errorHandler'
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务注册表
|
||||
* 负责注册所有系统服务
|
||||
*/
|
||||
export class ServiceRegistry {
|
||||
private static instance: ServiceRegistry
|
||||
private container: IServiceContainer
|
||||
|
||||
private constructor() {
|
||||
this.container = new ServiceContainerImpl()
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取服务注册表单例
|
||||
*/
|
||||
public static getInstance(): ServiceRegistry {
|
||||
if (!ServiceRegistry.instance) {
|
||||
ServiceRegistry.instance = new ServiceRegistry()
|
||||
}
|
||||
return ServiceRegistry.instance
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取服务容器实例
|
||||
*/
|
||||
public getContainer(): IServiceContainer {
|
||||
return this.container
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册所有服务
|
||||
* 注意:服务注册顺序应按照依赖关系排列
|
||||
*/
|
||||
public registerAllServices(): void {
|
||||
// 注册基本服务 - 这些服务没有其他依赖
|
||||
this.registerEventBuilder()
|
||||
this.registerExternalAppDiscovery()
|
||||
this.registerResourceService()
|
||||
this.registerErrorHandler()
|
||||
|
||||
// 注册核心服务 - 按照依赖关系顺序注册
|
||||
this.registerWindowFormService()
|
||||
this.registerSandboxEngine()
|
||||
this.registerLifecycleManager()
|
||||
this.registerSystemService()
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册事件构建器服务
|
||||
*/
|
||||
private registerEventBuilder(): void {
|
||||
this.container.register(ServiceIds.EVENT_BUILDER, async () => {
|
||||
const { EventBuilderImpl } = await import('@/events/impl/EventBuilderImpl')
|
||||
return new EventBuilderImpl()
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册外部应用发现服务
|
||||
*/
|
||||
private registerExternalAppDiscovery(): void {
|
||||
this.container.register(ServiceIds.EXTERNAL_APP_DISCOVERY, async () => {
|
||||
// 延迟导入避免循环依赖
|
||||
const { externalAppDiscovery } = await import('../ExternalAppDiscovery')
|
||||
return externalAppDiscovery
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册资源服务
|
||||
*/
|
||||
private registerResourceService(): void {
|
||||
this.container.register(
|
||||
ServiceIds.RESOURCE_SERVICE,
|
||||
async (container) => {
|
||||
// 延迟导入避免循环依赖
|
||||
const { ResourceService } = await import('../ResourceService')
|
||||
return new ResourceService(container.getService(ServiceIds.EVENT_BUILDER))
|
||||
},
|
||||
[ServiceIds.EVENT_BUILDER]
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册窗口表单服务
|
||||
*/
|
||||
private registerWindowFormService(): void {
|
||||
this.container.register(
|
||||
ServiceIds.WINDOW_FORM_SERVICE,
|
||||
async (container) => {
|
||||
// 延迟导入避免循环依赖
|
||||
const { WindowFormService } = await import('../WindowFormService')
|
||||
return new WindowFormService(container.getService(ServiceIds.EVENT_BUILDER))
|
||||
},
|
||||
[ServiceIds.EVENT_BUILDER]
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册沙箱引擎服务
|
||||
*/
|
||||
private registerSandboxEngine(): void {
|
||||
this.container.register(
|
||||
ServiceIds.SANDBOX_ENGINE,
|
||||
async (container) => {
|
||||
// 延迟导入避免循环依赖
|
||||
const { ApplicationSandboxEngine } = await import('../ApplicationSandboxEngine')
|
||||
return new ApplicationSandboxEngine(
|
||||
container.getService(ServiceIds.RESOURCE_SERVICE),
|
||||
container
|
||||
)
|
||||
},
|
||||
[ServiceIds.RESOURCE_SERVICE]
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册生命周期管理器服务
|
||||
*/
|
||||
private registerLifecycleManager(): void {
|
||||
this.container.register(
|
||||
ServiceIds.LIFECYCLE_MANAGER,
|
||||
async (container) => {
|
||||
// 延迟导入避免循环依赖
|
||||
const { ApplicationLifecycleManager } = await import('../ApplicationLifecycleManager')
|
||||
return new ApplicationLifecycleManager(
|
||||
container.getService(ServiceIds.RESOURCE_SERVICE),
|
||||
container.getService(ServiceIds.SANDBOX_ENGINE),
|
||||
container.getService(ServiceIds.WINDOW_FORM_SERVICE)
|
||||
)
|
||||
},
|
||||
[
|
||||
ServiceIds.RESOURCE_SERVICE,
|
||||
ServiceIds.SANDBOX_ENGINE,
|
||||
ServiceIds.WINDOW_FORM_SERVICE,
|
||||
ServiceIds.EXTERNAL_APP_DISCOVERY
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册系统服务集成服务
|
||||
*/
|
||||
private registerSystemService(): void {
|
||||
this.container.register(
|
||||
ServiceIds.SYSTEM_SERVICE,
|
||||
async (container) => {
|
||||
// 延迟导入避免循环依赖
|
||||
const { SystemServiceIntegration } = await import('../SystemServiceIntegration')
|
||||
return new SystemServiceIntegration(container)
|
||||
},
|
||||
[
|
||||
ServiceIds.RESOURCE_SERVICE,
|
||||
ServiceIds.WINDOW_FORM_SERVICE,
|
||||
ServiceIds.SANDBOX_ENGINE,
|
||||
ServiceIds.LIFECYCLE_MANAGER,
|
||||
ServiceIds.EVENT_BUILDER,
|
||||
ServiceIds.ERROR_HANDLER
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册错误处理服务
|
||||
*/
|
||||
private registerErrorHandler(): void {
|
||||
this.container.register(
|
||||
ServiceIds.ERROR_HANDLER,
|
||||
async () => {
|
||||
// 延迟导入避免循环依赖
|
||||
const { ErrorHandlerImpl } = await import('../impl/ErrorHandlerImpl')
|
||||
return new ErrorHandlerImpl()
|
||||
},
|
||||
[] // 错误处理服务应尽量减少依赖,避免在错误处理过程中出现循环依赖
|
||||
)
|
||||
}
|
||||
}
|
||||
179
src/services/di/SystemBootstrapper.ts
Normal file
179
src/services/di/SystemBootstrapper.ts
Normal file
@@ -0,0 +1,179 @@
|
||||
import { ServiceRegistry } from './ServiceRegistry'
|
||||
import { ServiceProvider } from './ServiceProvider'
|
||||
import { SystemServiceIntegration } from '../SystemServiceIntegration'
|
||||
import { ServiceContainerImpl } from './ServiceContainerImpl'
|
||||
|
||||
/**
|
||||
* 系统启动器
|
||||
* 负责初始化整个系统,包括服务容器、服务注册和启动核心服务
|
||||
*/
|
||||
export class SystemBootstrapper {
|
||||
private static instance: SystemBootstrapper
|
||||
private serviceContainer: ServiceContainerImpl
|
||||
private systemService: SystemServiceIntegration | null = null
|
||||
private initialized = false
|
||||
|
||||
private constructor() {
|
||||
this.serviceContainer = new ServiceContainerImpl()
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取系统启动器实例
|
||||
*/
|
||||
public static getInstance(): SystemBootstrapper {
|
||||
if (!SystemBootstrapper.instance) {
|
||||
SystemBootstrapper.instance = new SystemBootstrapper()
|
||||
}
|
||||
return SystemBootstrapper.instance
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动整个系统
|
||||
* @param config 系统配置参数
|
||||
* @returns 启动成功返回true,失败返回false
|
||||
*/
|
||||
public async bootstrap(config?: {
|
||||
debug?: boolean
|
||||
autoCleanup?: boolean
|
||||
cleanupInterval?: number
|
||||
}): Promise<boolean> {
|
||||
if (this.initialized) {
|
||||
console.warn('系统已经启动')
|
||||
return true
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('开始启动系统...', config)
|
||||
|
||||
// 1. 初始化服务提供者
|
||||
this.initializeServiceProvider()
|
||||
|
||||
// 2. 初始化系统服务集成层
|
||||
this.initializeSystemService(config || {})
|
||||
|
||||
// 3. 启动所有服务
|
||||
await this.startAllServices()
|
||||
|
||||
this.initialized = true
|
||||
console.log('系统启动成功')
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error('系统启动失败:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化服务提供者
|
||||
* 注册并初始化所有服务
|
||||
*/
|
||||
private initializeServiceProvider(): void {
|
||||
console.log('初始化服务提供者...')
|
||||
|
||||
// 初始化服务提供者,这会注册并初始化所有服务
|
||||
ServiceProvider.initialize()
|
||||
console.log('服务提供者初始化完成')
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化系统服务集成层
|
||||
* 创建并配置SystemServiceIntegration实例
|
||||
*/
|
||||
private initializeSystemService(config: {
|
||||
debug?: boolean
|
||||
autoCleanup?: boolean
|
||||
cleanupInterval?: number
|
||||
}): void {
|
||||
console.log('初始化系统服务集成层...')
|
||||
|
||||
// 获取服务容器
|
||||
const container = ServiceRegistry.getInstance().getContainer()
|
||||
|
||||
// 创建系统服务集成实例,使用传入的配置
|
||||
this.systemService = new SystemServiceIntegration(container, {
|
||||
debug: config.debug ?? true,
|
||||
autoCleanup: config.autoCleanup ?? true,
|
||||
cleanupInterval: config.cleanupInterval ?? 5 * 60 * 1000 // 默认5分钟
|
||||
})
|
||||
|
||||
console.log('系统服务集成层初始化完成')
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动所有服务
|
||||
*/
|
||||
private async startAllServices(): Promise<void> {
|
||||
console.log('启动所有服务...')
|
||||
|
||||
if (!this.systemService) {
|
||||
throw new Error('系统服务集成层未初始化')
|
||||
}
|
||||
|
||||
// 初始化系统服务
|
||||
await this.systemService.initialize()
|
||||
|
||||
console.log('所有服务启动完成')
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取系统服务实例
|
||||
*/
|
||||
public getSystemService(): SystemServiceIntegration | null {
|
||||
return this.systemService
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查系统是否已初始化
|
||||
*/
|
||||
public isInitialized(): boolean {
|
||||
return this.initialized
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭系统
|
||||
*/
|
||||
public async shutdown(): Promise<void> {
|
||||
if (!this.initialized) {
|
||||
console.warn('系统未启动')
|
||||
return
|
||||
}
|
||||
|
||||
console.log('开始关闭系统...')
|
||||
|
||||
try {
|
||||
// 关闭系统服务
|
||||
if (this.systemService) {
|
||||
await this.systemService.shutdown()
|
||||
}
|
||||
|
||||
// 重置状态
|
||||
this.systemService = null
|
||||
this.initialized = false
|
||||
|
||||
console.log('系统已关闭')
|
||||
} catch (error) {
|
||||
console.error('关闭系统时发生错误:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重启系统
|
||||
*/
|
||||
public async restart(): Promise<boolean> {
|
||||
console.log('重启系统...')
|
||||
|
||||
try {
|
||||
await this.shutdown()
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000))
|
||||
return await this.bootstrap()
|
||||
} catch (error) {
|
||||
console.error('重启系统失败:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出系统启动器单例实例
|
||||
*/
|
||||
export const systemBootstrapper = SystemBootstrapper.getInstance()
|
||||
94
src/services/di/example.ts
Normal file
94
src/services/di/example.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* 依赖注入系统使用示例
|
||||
*/
|
||||
|
||||
// 1. 系统启动示例 - 通常在应用入口文件中使用
|
||||
import { systemBootstrapper } from './SystemBootstrapper'
|
||||
import { ServiceProvider, Inject } from './ServiceProvider'
|
||||
import { ServiceIds } from './ServiceRegistry'
|
||||
|
||||
// 启动系统(通常在应用入口点调用一次)
|
||||
async function startApplication() {
|
||||
try {
|
||||
console.log('正在启动应用...')
|
||||
|
||||
// 启动整个系统,包括初始化服务容器和所有服务
|
||||
const success = await systemBootstrapper.bootstrap()
|
||||
|
||||
if (!success) {
|
||||
throw new Error('系统启动失败')
|
||||
}
|
||||
|
||||
console.log('应用启动成功!')
|
||||
|
||||
// 应用初始化完成后,可以开始使用各种服务
|
||||
initializeApplication()
|
||||
} catch (error) {
|
||||
console.error('应用启动失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// 应用初始化
|
||||
function initializeApplication() {
|
||||
// 2. 使用静态服务提供者访问服务
|
||||
const windowService = ServiceProvider.getWindowFormService()
|
||||
const resourceService = ServiceProvider.getResourceService()
|
||||
|
||||
console.log('访问服务示例:', {
|
||||
windowServiceAvailable: !!windowService,
|
||||
resourceServiceAvailable: !!resourceService
|
||||
})
|
||||
|
||||
// 3. 创建并初始化一个使用依赖注入的组件
|
||||
const appComponent = new ApplicationComponent()
|
||||
appComponent.initialize()
|
||||
}
|
||||
|
||||
// 4. 在组件中使用依赖注入
|
||||
class ApplicationComponent {
|
||||
// 使用装饰器自动注入服务
|
||||
@Inject(ServiceIds.WINDOW_FORM_SERVICE)
|
||||
private windowFormService: any
|
||||
|
||||
@Inject(ServiceIds.RESOURCE_SERVICE)
|
||||
private resourceService: any
|
||||
|
||||
@Inject(ServiceIds.LIFECYCLE_MANAGER)
|
||||
private lifecycleManager: any
|
||||
|
||||
initialize() {
|
||||
console.log('组件初始化,服务已注入:', {
|
||||
windowFormService: !!this.windowFormService,
|
||||
resourceService: !!this.resourceService,
|
||||
lifecycleManager: !!this.lifecycleManager
|
||||
})
|
||||
|
||||
// 使用注入的服务
|
||||
this.setupComponent()
|
||||
}
|
||||
|
||||
private setupComponent() {
|
||||
// 示例:使用窗口服务创建一个新窗口
|
||||
// 注意:这只是示例代码,实际使用时需要根据具体服务API调整
|
||||
console.log('组件正在使用注入的服务设置UI...')
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 动态获取服务示例
|
||||
function dynamicServiceExample(serviceId: string) {
|
||||
// 使用get方法动态获取服务
|
||||
try {
|
||||
const service = ServiceProvider.getService(serviceId as any)
|
||||
console.log(`动态获取服务[${serviceId}]:`, !!service)
|
||||
return service
|
||||
} catch (error) {
|
||||
console.error(`无法获取服务[${serviceId}]:`, error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// 导出示例函数供其他文件使用
|
||||
export { startApplication, dynamicServiceExample, ApplicationComponent }
|
||||
|
||||
// 注意:在实际应用中,你会在main.ts或应用入口文件中调用startApplication()
|
||||
// startApplication(); // 取消注释以启动应用
|
||||
91
src/services/di/types.d.ts
vendored
Normal file
91
src/services/di/types.d.ts
vendored
Normal file
@@ -0,0 +1,91 @@
|
||||
import { IServiceContainer } from './IServiceContainer'
|
||||
import { ServiceIds } from './ServiceRegistry'
|
||||
|
||||
/**
|
||||
* 定义所有服务类型映射
|
||||
* 这个接口用于在ServiceProvider中提供强类型的服务访问
|
||||
*/
|
||||
export interface ServiceTypeMap {
|
||||
[ServiceIds.RESOURCE_SERVICE]: any // ResourceService
|
||||
[ServiceIds.WINDOW_FORM_SERVICE]: any // WindowFormService
|
||||
[ServiceIds.SANDBOX_ENGINE]: any // ApplicationSandboxEngine
|
||||
[ServiceIds.LIFECYCLE_MANAGER]: any // ApplicationLifecycleManager
|
||||
[ServiceIds.SYSTEM_SERVICE]: any // SystemServiceIntegration
|
||||
[ServiceIds.EVENT_BUILDER]: any // IEventBuilder<any>
|
||||
[ServiceIds.EXTERNAL_APP_DISCOVERY]: any // 外部应用发现服务
|
||||
[ServiceIds.ERROR_HANDLER]: any // 错误处理服务
|
||||
}
|
||||
|
||||
/**
|
||||
* 扩展IServiceContainer接口,提供强类型的get方法
|
||||
*/
|
||||
declare module './IServiceContainer' {
|
||||
export interface IServiceContainer {
|
||||
/**
|
||||
* 获取服务实例(带类型支持)
|
||||
* @param id 服务ID
|
||||
* @returns 服务实例,类型根据服务ID自动推断
|
||||
*/
|
||||
getService<T extends keyof ServiceTypeMap>(id: T): ServiceTypeMap[T]
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 扩展ServiceProvider类的静态方法类型
|
||||
*/
|
||||
declare module './ServiceProvider' {
|
||||
// 仅扩展现有ServiceProvider类,不重新声明
|
||||
interface ServiceProvider {
|
||||
/**
|
||||
* 获取服务实例(带类型支持)
|
||||
* @param id 服务ID
|
||||
* @returns 服务实例,类型根据服务ID自动推断
|
||||
*/
|
||||
static getService<T extends keyof ServiceTypeMap>(id: T): ServiceTypeMap[T]
|
||||
|
||||
/**
|
||||
* 获取资源服务
|
||||
*/
|
||||
static getResourceService(): ServiceTypeMap[typeof ServiceIds.RESOURCE_SERVICE]
|
||||
|
||||
/**
|
||||
* 获取窗口表单服务
|
||||
*/
|
||||
static getWindowFormService(): ServiceTypeMap[typeof ServiceIds.WINDOW_FORM_SERVICE]
|
||||
|
||||
/**
|
||||
* 获取沙箱引擎
|
||||
*/
|
||||
static getSandboxEngine(): ServiceTypeMap[typeof ServiceIds.SANDBOX_ENGINE]
|
||||
|
||||
/**
|
||||
* 获取生命周期管理器
|
||||
*/
|
||||
static getLifecycleManager(): ServiceTypeMap[typeof ServiceIds.LIFECYCLE_MANAGER]
|
||||
|
||||
/**
|
||||
* 获取系统服务
|
||||
*/
|
||||
static getSystemService(): ServiceTypeMap[typeof ServiceIds.SYSTEM_SERVICE]
|
||||
|
||||
/**
|
||||
* 获取事件构建器
|
||||
*/
|
||||
static getEventBuilder(): ServiceTypeMap[typeof ServiceIds.EVENT_BUILDER]
|
||||
|
||||
/**
|
||||
* 获取外部应用发现服务
|
||||
*/
|
||||
static getExternalAppDiscovery(): ServiceTypeMap[typeof ServiceIds.EXTERNAL_APP_DISCOVERY]
|
||||
|
||||
/**
|
||||
* 获取错误处理服务
|
||||
*/
|
||||
static getErrorHandler(): ServiceTypeMap[typeof ServiceIds.ERROR_HANDLER]
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 声明Inject装饰器类型
|
||||
*/
|
||||
declare function Inject<T extends keyof ServiceTypeMap>(serviceId: T): PropertyDecorator
|
||||
103
src/services/example/ErrorHandlerExample.ts
Normal file
103
src/services/example/ErrorHandlerExample.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
import { ServiceProvider } from '../di/ServiceProvider'
|
||||
import { ServiceIds } from '../di/ServiceRegistry'
|
||||
import type { IErrorHandler, ErrorContext } from '../IErrorHandler'
|
||||
|
||||
/**
|
||||
* 错误处理服务使用示例
|
||||
*/
|
||||
export class ErrorHandlerExample {
|
||||
private errorHandler: IErrorHandler
|
||||
|
||||
constructor() {
|
||||
// 通过服务提供者获取错误处理器实例
|
||||
this.errorHandler = ServiceProvider.getService<IErrorHandler>(ServiceIds.ERROR_HANDLER)
|
||||
}
|
||||
|
||||
/**
|
||||
* 演示不同类型错误的处理
|
||||
*/
|
||||
public demonstrateErrorHandling(): void {
|
||||
console.log('=== 开始演示错误处理服务 ===')
|
||||
|
||||
// 1. 处理标准Error对象
|
||||
try {
|
||||
throw new Error('这是一个标准错误')
|
||||
} catch (error) {
|
||||
const context: ErrorContext = {
|
||||
source: 'ErrorHandlerExample',
|
||||
operation: 'demonstrateStandardError',
|
||||
appId: 'example-app-123'
|
||||
}
|
||||
this.errorHandler.handleError(error, context)
|
||||
}
|
||||
|
||||
// 2. 处理类型错误
|
||||
try {
|
||||
const obj: any = null
|
||||
obj.method() // 这会抛出TypeError
|
||||
} catch (error) {
|
||||
this.errorHandler.handleError(error, {
|
||||
source: 'ErrorHandlerExample',
|
||||
operation: 'demonstrateTypeError',
|
||||
additionalInfo: '尝试在null上调用方法'
|
||||
})
|
||||
}
|
||||
|
||||
// 3. 处理未捕获的Promise错误
|
||||
console.log('演示未捕获的Promise错误...')
|
||||
// 注意:这个错误会被全局错误处理器捕获
|
||||
Promise.reject(new Error('这是一个未处理的Promise错误'))
|
||||
|
||||
// 4. 获取最近的错误记录
|
||||
setTimeout(() => {
|
||||
const recentErrors = this.errorHandler.getRecentErrors(2)
|
||||
console.log('\n=== 最近的错误记录 ===')
|
||||
recentErrors.forEach(record => {
|
||||
console.log(`错误ID: ${record.id}`)
|
||||
console.log(`时间: ${record.timestamp.toISOString()}`)
|
||||
console.log(`处理状态: ${record.handled ? '已处理' : '未处理'}`)
|
||||
console.log(`上下文:`, record.context)
|
||||
})
|
||||
}, 100)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在组件或服务中使用错误处理器的示例
|
||||
*/
|
||||
export function useErrorHandlerInComponent() {
|
||||
const errorHandler = ServiceProvider.getService<IErrorHandler>(ServiceIds.ERROR_HANDLER)
|
||||
|
||||
// 在组件方法中使用
|
||||
function performRiskyOperation() {
|
||||
try {
|
||||
// 执行可能失败的操作
|
||||
if (Math.random() > 0.5) {
|
||||
throw new Error('操作随机失败')
|
||||
}
|
||||
return '操作成功'
|
||||
} catch (error) {
|
||||
// 使用错误处理器记录和处理错误
|
||||
errorHandler.handleError(error, {
|
||||
source: 'MyComponent',
|
||||
operation: 'performRiskyOperation',
|
||||
componentProps: { /* 组件属性信息 */ }
|
||||
})
|
||||
|
||||
// 可以选择返回一个默认值或重新抛出
|
||||
return '操作失败,但已正确处理'
|
||||
}
|
||||
}
|
||||
|
||||
return { performRiskyOperation }
|
||||
}
|
||||
|
||||
// 导出一个立即执行的示例函数,方便直接测试
|
||||
export function runErrorHandlerExample() {
|
||||
try {
|
||||
const example = new ErrorHandlerExample()
|
||||
example.demonstrateErrorHandling()
|
||||
} catch (error) {
|
||||
console.error('示例执行失败:', error)
|
||||
}
|
||||
}
|
||||
154
src/services/impl/ErrorHandlerImpl.ts
Normal file
154
src/services/impl/ErrorHandlerImpl.ts
Normal file
@@ -0,0 +1,154 @@
|
||||
import type { IErrorHandler, ErrorContext, ErrorRecord } from '../IErrorHandler'
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
|
||||
/**
|
||||
* 全局错误处理器实现
|
||||
*/
|
||||
export class ErrorHandlerImpl implements IErrorHandler {
|
||||
private errorRecords: ErrorRecord[] = []
|
||||
private maxRecords = 100
|
||||
private isGlobalHandlersSetup = false
|
||||
|
||||
constructor() {
|
||||
// 初始化时可以设置全局错误处理器
|
||||
this.setupGlobalErrorHandlers()
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理应用错误
|
||||
* @param error 错误对象
|
||||
* @param context 错误上下文信息
|
||||
* @returns 是否成功处理了错误
|
||||
*/
|
||||
public handleError(error: Error | any, context: ErrorContext = {}): boolean {
|
||||
try {
|
||||
// 创建错误记录
|
||||
const errorRecord: ErrorRecord = {
|
||||
id: uuidv4(),
|
||||
error,
|
||||
context,
|
||||
timestamp: new Date(),
|
||||
handled: false
|
||||
}
|
||||
|
||||
// 保存错误记录
|
||||
this.addErrorRecord(errorRecord)
|
||||
|
||||
// 根据错误类型进行处理
|
||||
if (error instanceof Error) {
|
||||
this.logError(error, context)
|
||||
this.reportError(error, context)
|
||||
} else {
|
||||
// 非标准错误对象
|
||||
this.logUnknownError(error, context)
|
||||
}
|
||||
|
||||
errorRecord.handled = true
|
||||
return true
|
||||
} catch (handlerError) {
|
||||
console.error('错误处理器自身出错:', handlerError)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理未捕获的异常
|
||||
*/
|
||||
public setupGlobalErrorHandlers(): void {
|
||||
if (this.isGlobalHandlersSetup) {
|
||||
return
|
||||
}
|
||||
|
||||
// 捕获未处理的Promise错误
|
||||
window.addEventListener('unhandledrejection', (event) => {
|
||||
this.handleError(event.reason, {
|
||||
source: 'unhandledrejection',
|
||||
operation: 'Promise处理'
|
||||
})
|
||||
})
|
||||
|
||||
// 捕获全局错误
|
||||
window.addEventListener('error', (event) => {
|
||||
const error = event.error || new Error(event.message)
|
||||
this.handleError(error, {
|
||||
source: 'window.error',
|
||||
operation: event.filename || window.location.pathname,
|
||||
lineNumber: event.lineno,
|
||||
columnNumber: event.colno
|
||||
})
|
||||
})
|
||||
|
||||
// Vue应用的错误处理可以在main.ts中配置
|
||||
|
||||
this.isGlobalHandlersSetup = true
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取最近的错误记录
|
||||
* @param limit 获取的最大数量
|
||||
*/
|
||||
public getRecentErrors(limit: number = 10): ErrorRecord[] {
|
||||
return this.errorRecords
|
||||
.slice()
|
||||
.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime())
|
||||
.slice(0, limit)
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加错误记录到历史
|
||||
*/
|
||||
private addErrorRecord(record: ErrorRecord): void {
|
||||
this.errorRecords.unshift(record)
|
||||
|
||||
// 限制记录数量
|
||||
if (this.errorRecords.length > this.maxRecords) {
|
||||
this.errorRecords = this.errorRecords.slice(0, this.maxRecords)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录标准错误
|
||||
*/
|
||||
private logError(error: Error, context: ErrorContext): void {
|
||||
console.error(`[错误处理] ${context.source || '未知来源'}: ${error.message}`, {
|
||||
error,
|
||||
stack: error.stack,
|
||||
context
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录未知类型错误
|
||||
*/
|
||||
private logUnknownError(error: any, context: ErrorContext): void {
|
||||
console.error(`[错误处理] ${context.source || '未知来源'}: 发生未知类型错误`, {
|
||||
error,
|
||||
context
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 报告错误(可以扩展为发送到错误监控服务)
|
||||
*/
|
||||
private reportError(error: Error, context: ErrorContext): void {
|
||||
// 在实际项目中,这里可以将错误发送到远程监控服务
|
||||
// 例如:sentry、logrocket等
|
||||
// 现在只是记录到控制台
|
||||
console.debug('[错误报告] 准备发送错误信息...')
|
||||
|
||||
// 模拟异步错误报告
|
||||
setTimeout(() => {
|
||||
console.debug(`[错误报告] 错误已记录,ID: ${context.source || 'unknown'}`)
|
||||
}, 0)
|
||||
}
|
||||
}
|
||||
|
||||
// 创建单例实例
|
||||
let instance: ErrorHandlerImpl | null = null
|
||||
|
||||
export function getErrorHandlerInstance(): ErrorHandlerImpl {
|
||||
if (!instance) {
|
||||
instance = new ErrorHandlerImpl()
|
||||
}
|
||||
return instance
|
||||
}
|
||||
Reference in New Issue
Block a user