41 行
952 B
TypeScript
41 行
952 B
TypeScript
|
|
/**
|
||
|
|
* Web 端崩溃捕获器
|
||
|
|
*/
|
||
|
|
|
||
|
|
type ErrorHandler = (error: Error, tags?: Record<string, unknown>) => void
|
||
|
|
|
||
|
|
let _started = false
|
||
|
|
let _handler: ErrorHandler | null = null
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 启动崩溃捕获
|
||
|
|
*/
|
||
|
|
export function startCrashCapture(handler: ErrorHandler): void {
|
||
|
|
if (_started) return
|
||
|
|
_started = true
|
||
|
|
_handler = handler
|
||
|
|
|
||
|
|
// 捕获未处理的错误
|
||
|
|
window.addEventListener('error', (event) => {
|
||
|
|
if (event.error) {
|
||
|
|
handler(event.error, { type: 'uncaught_error', filename: event.filename, lineno: event.lineno, colno: event.colno })
|
||
|
|
}
|
||
|
|
})
|
||
|
|
|
||
|
|
// 捕获未处理的 Promise rejection
|
||
|
|
window.addEventListener('unhandledrejection', (event) => {
|
||
|
|
const error = event.reason instanceof Error
|
||
|
|
? event.reason
|
||
|
|
: new Error(String(event.reason))
|
||
|
|
handler(error, { type: 'unhandled_rejection' })
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 停止崩溃捕获
|
||
|
|
*/
|
||
|
|
export function stopCrashCapture(): void {
|
||
|
|
_started = false
|
||
|
|
_handler = null
|
||
|
|
}
|