3987b8d7fe
- 此前全树 0 处全局错误处理器:装 app.config.errorHandler + window error + unhandledrejection, 每条都留可诊断记录、界面只出中文、处理器自身异常不重抛也不白屏(9 例判据)。 - safeHttpUrl 未覆盖的 3 处(两个品牌 Tab 与 useVersionUpdate 直装服务端 file_url)收口; 令牌键 aiimage_auth_token 由 4 处各自定义 + 2 处内联收成唯一定义点。 - 「localStorage 有 uid 就免校验」改走 auth-gate 单点,剩余例外台账化且同口径必须能抓到 评审点名的原写法(6 例);卸载配对 3 处补齐 + 全树判据(7 例)。 - task-status-text 把 CANCELLED 显示成"执行中"改对,CANCELED/CANCELLED 两拼写都映射(4 例)。 - 主审计补的四处修复:新判据里两处拿数组和 0 比(怎么写都红);静默 catch 的"用户可见出口" 符号表认不出本仓 userNotice 与注入式 notify,把真报了用户的 catch 判成静默; 新错误出口带来的 2 个 try/catch 按棘轮合同写理由进基线(296→298,silent 一格没涨)。 - 验收:node --test 820 例 0 红、npx vue-tsc --noEmit rc=0。
242 lines
12 KiB
TypeScript
242 lines
12 KiB
TypeScript
import { test } from 'node:test'
|
|
import assert from 'node:assert/strict'
|
|
import { readdirSync, readFileSync } from 'node:fs'
|
|
import { fileURLToPath } from 'node:url'
|
|
import { dirname, join, resolve, relative, sep } from 'node:path'
|
|
import {
|
|
APP_ERROR_NOTICE_COOLDOWN_MS,
|
|
APP_ERROR_NOTICE_TEXT,
|
|
APP_ERROR_RECORD_LIMIT,
|
|
clearAppErrorRecords,
|
|
describeAppError,
|
|
disposeGlobalErrorGuard,
|
|
errorRawText,
|
|
getAppErrorRecords,
|
|
installGlobalErrorGuard,
|
|
userTextForError,
|
|
} from '../src/shared/utils/app-error.ts'
|
|
import type { ErrorGuardApp } from '../src/shared/utils/app-error.ts'
|
|
|
|
/**
|
|
* 全局错误处理器(2026-10-09 评审稳定面 5.0 的第一条:全树 `app.config.errorHandler`、
|
|
* `unhandledrejection`、`window.onerror` 各 0 处;非零对照 `router.onError` 恰 1 处)。
|
|
*
|
|
* 这条判据主要跑行为:造一个假 app 与假 window 把三个出口装上,然后真去触发它们,
|
|
* 看"用户看到的话"和"可诊断的记录"是否都出来——静态计数只能证明代码在场,证明不了它会响。
|
|
* 静态那半边留给接线(main.ts 装了、App.vue 卸了),同样配非零对照与注入自证。
|
|
*/
|
|
|
|
const here = dirname(fileURLToPath(import.meta.url))
|
|
const ROOT = resolve(here, '..')
|
|
const SRC = resolve(ROOT, 'src')
|
|
|
|
const CJK = /[㐀-䶿一-鿿]/
|
|
|
|
interface FakeHost {
|
|
added: Array<{ type: string; listener: (event: never) => void }>
|
|
removed: string[]
|
|
emit: (type: string, event: unknown) => void
|
|
}
|
|
|
|
/** 每个假世界自己的时钟起点:模块级冷却状态会跨用例,起点不隔开就会互相吃掉提示。 */
|
|
let worldSeq = 0
|
|
|
|
function makeWorld() {
|
|
const notices: string[] = []
|
|
const lines: string[] = []
|
|
const listeners = new Map<string, Array<(event: never) => void>>()
|
|
const removed: string[] = []
|
|
worldSeq += 1
|
|
let clock = worldSeq * 10_000_000
|
|
const host = {
|
|
addEventListener: (type: string, listener: (event: never) => void) => {
|
|
listeners.set(type, [...(listeners.get(type) ?? []), listener])
|
|
},
|
|
removeEventListener: (type: string) => {
|
|
removed.push(type)
|
|
listeners.delete(type)
|
|
},
|
|
}
|
|
const app: ErrorGuardApp = { config: {} }
|
|
const emit = (type: string, event: unknown) => {
|
|
for (const listener of listeners.get(type) ?? []) (listener as (e: unknown) => void)(event)
|
|
}
|
|
const advance = (ms: number) => { clock += ms }
|
|
const dispose = installGlobalErrorGuard(app, {
|
|
notify: (text) => notices.push(text),
|
|
record: (line) => lines.push(line),
|
|
now: () => clock,
|
|
}, host)
|
|
const fakeHost: FakeHost = {
|
|
added: [...listeners.entries()].map(([type, ls]) => ({ type, listener: ls[0] })),
|
|
removed,
|
|
emit,
|
|
}
|
|
return { app, notices, lines, dispose, advance, fakeHost, listenerTypes: () => [...listeners.keys()].sort() }
|
|
}
|
|
|
|
function sourceFiles(dir: string): string[] {
|
|
const out: string[] = []
|
|
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
const full = join(dir, entry.name)
|
|
if (entry.isDirectory()) out.push(...sourceFiles(full))
|
|
else if (entry.name.endsWith('.vue') || entry.name.endsWith('.ts')) out.push(full)
|
|
}
|
|
return out
|
|
}
|
|
|
|
const ENTRIES = sourceFiles(SRC).map((file) => ({
|
|
rel: relative(ROOT, file).split(sep).join('/'),
|
|
source: readFileSync(file, 'utf-8'),
|
|
}))
|
|
|
|
function read(rel: string): string {
|
|
return ENTRIES.find((e) => e.rel === rel)?.source ?? readFileSync(join(ROOT, ...rel.split('/')), 'utf-8')
|
|
}
|
|
|
|
/** 三个出口的在场判据(装配面)。`from` 用于注入自证:把装配删掉就该判红。 */
|
|
function guardWiring(source: string) {
|
|
// `addEventListener(` 与可选链写法 `addEventListener?.(` 都算(源码里用的是后者)
|
|
return {
|
|
vueErrorHandler: /app\.config\.errorHandler\s*=|config\.errorHandler\s*=\s*\(?\s*(?:err|error)\b/.test(source),
|
|
rejection: /addEventListener\??\.?\(\s*['"]unhandledrejection['"]/.test(source),
|
|
windowError: /addEventListener\??\.?\(\s*['"]error['"]/.test(source),
|
|
}
|
|
}
|
|
|
|
test('装上的那一刻三个出口都在,卸载时全部摘掉', () => {
|
|
clearAppErrorRecords()
|
|
const world = makeWorld()
|
|
assert.equal(typeof world.app.config.errorHandler, 'function', 'app.config.errorHandler 没装上')
|
|
assert.deepEqual(world.listenerTypes(), ['error', 'unhandledrejection'], 'window 上的两个出口少一个')
|
|
world.dispose()
|
|
assert.equal(world.app.config.errorHandler, undefined, '卸载后 errorHandler 还挂着')
|
|
assert.deepEqual(world.fakeHost.removed.sort(), ['error', 'unhandledrejection'], '卸载没有 removeEventListener 配对')
|
|
})
|
|
|
|
test('三个出口都真的响:记录一定落,界面只说中文', () => {
|
|
clearAppErrorRecords()
|
|
const world = makeWorld()
|
|
// ① Vue 渲染期抛错(英文异常原文,绝不能出现在界面上)
|
|
world.app.config.errorHandler?.(new Error('Cannot read properties of undefined'), null, 'render')
|
|
// 越过冷却再发第二条,避免被去重吃掉(去重本身另有用例)
|
|
world.advance(APP_ERROR_NOTICE_COOLDOWN_MS + 1)
|
|
// ② 顶层同步异常
|
|
world.fakeHost.emit('error', { message: 'Uncaught ReferenceError: x is not defined', error: undefined })
|
|
world.advance(APP_ERROR_NOTICE_COOLDOWN_MS + 1)
|
|
// ③ 没人接的 Promise
|
|
world.fakeHost.emit('unhandledrejection', { reason: 'Network Error' })
|
|
|
|
assert.equal(world.notices.length, 3, `三条错误只出声 ${world.notices.length} 次`)
|
|
for (const text of world.notices) {
|
|
assert.ok(CJK.test(text), `界面提示必须含中文:${text}`)
|
|
for (const english of ['Cannot read properties', 'ReferenceError', 'Network Error', 'Uncaught']) {
|
|
assert.ok(!text.includes(english), `英文异常原文漏到了界面上:${text}`)
|
|
}
|
|
}
|
|
// 记录里必须有原文与出处(否则支持同学拿什么对后端日志)
|
|
assert.equal(world.lines.length, 3, '记录条数与错误条数不一致,有错误被吞了')
|
|
assert.match(world.lines[0], /^\[vue:render\] Cannot read properties of undefined/)
|
|
assert.match(world.lines[1], /^\[window\.error\] Uncaught ReferenceError/)
|
|
assert.match(world.lines[2], /^\[unhandledrejection\] Network Error/)
|
|
assert.equal(getAppErrorRecords().length, 3, '内存环里也该留着这 3 条')
|
|
})
|
|
|
|
test('中文原文照原样透出,不做无谓改写', () => {
|
|
const world = makeWorld()
|
|
world.advance(APP_ERROR_NOTICE_COOLDOWN_MS + 1)
|
|
world.app.config.errorHandler?.(new Error('任务已被取消,请重新提交'), null, 'watcher')
|
|
assert.deepEqual(world.notices, ['任务已被取消,请重新提交'])
|
|
assert.equal(userTextForError('Similar ASIN result rows are empty'), APP_ERROR_NOTICE_TEXT)
|
|
assert.equal(errorRawText(null), '')
|
|
assert.equal(describeAppError('vue:x', null), '[vue:x] (没有错误原文)')
|
|
})
|
|
|
|
test('同一个错在渲染循环里刷屏时:只说一次,但被压掉的条数记在案', () => {
|
|
const world = makeWorld()
|
|
for (let i = 0; i < 5; i += 1) {
|
|
world.app.config.errorHandler?.(new Error(`loop ${i}`), null, 'render')
|
|
}
|
|
assert.equal(world.notices.length, 1, '5 条同场错误刷出了多条弹窗')
|
|
assert.equal(world.lines.length, 5, '被去重的那几条不能连记录一起消失')
|
|
world.advance(APP_ERROR_NOTICE_COOLDOWN_MS + 1)
|
|
world.app.config.errorHandler?.(new Error('after cooldown'), null, 'render')
|
|
assert.deepEqual(world.notices[1], `${APP_ERROR_NOTICE_TEXT}(同样的问题这期间还出现过 4 次)`)
|
|
})
|
|
|
|
test('处理器自己抛了也不许把页面搞白屏:兜住、留痕、再说一句中文', () => {
|
|
const notices: string[] = []
|
|
const lines: string[] = []
|
|
const boom = {
|
|
addEventListener: () => { /* 假 window 不需要 */ },
|
|
removeEventListener: () => { /* 同上 */ },
|
|
}
|
|
const app: ErrorGuardApp = { config: {} }
|
|
installGlobalErrorGuard(app, {
|
|
notify: (text) => {
|
|
notices.push(text)
|
|
if (notices.length === 1) throw new Error('弹窗组件挂了')
|
|
},
|
|
record: (line) => lines.push(line),
|
|
now: () => (worldSeq += 1) * 10_000_000,
|
|
}, boom)
|
|
// 第一条:notify 抛错 → 处理器不得把异常抛回 Vue,否则这次渲染直接白屏
|
|
assert.doesNotThrow(() => app.config.errorHandler?.(new Error('first'), null, 'render'))
|
|
assert.ok(notices.some((text) => CJK.test(text)), '处理器自身异常时没给出中文提示')
|
|
// 第二条:同样的路径再来一次,依然不抛
|
|
assert.doesNotThrow(() => app.config.errorHandler?.(new Error('second'), null, 'render'))
|
|
})
|
|
|
|
test('记录环有上限:挤掉最老的而不是无限攒', () => {
|
|
clearAppErrorRecords()
|
|
const world = makeWorld()
|
|
for (let i = 0; i < APP_ERROR_RECORD_LIMIT + 8; i += 1) {
|
|
world.advance(APP_ERROR_NOTICE_COOLDOWN_MS + 1)
|
|
world.app.config.errorHandler?.(new Error(`e${i}`), null, 'render')
|
|
}
|
|
const records = getAppErrorRecords()
|
|
assert.equal(records.length, APP_ERROR_RECORD_LIMIT, `记录环长到了 ${records.length}`)
|
|
assert.match(records[records.length - 1], /e27/)
|
|
assert.ok(!records.some((line) => line.includes('[vue:render] e0')), '最老的一条没被挤掉')
|
|
})
|
|
|
|
test('接线钉子:main.ts 装了、App.vue 卸了,全树三个出口都在场', () => {
|
|
const main = read('src/main.ts')
|
|
const appVue = read('src/App.vue')
|
|
assert.match(main, /installGlobalErrorGuard\(\s*app\s*,/, 'main.ts 没把处理器装到 app 上')
|
|
assert.match(main, /notify:.*ElMessage\.error/s, '界面出口没接 ElMessage')
|
|
assert.match(appVue, /onBeforeUnmount\(\(\)\s*=>\s*\{[^}]*disposeGlobalErrorGuard\(\)/, 'App.vue 没有卸载配对')
|
|
const present = {
|
|
vueErrorHandler: ENTRIES.filter(({ source }) => guardWiring(source).vueErrorHandler).length,
|
|
rejection: ENTRIES.filter(({ source }) => guardWiring(source).rejection).length,
|
|
windowError: ENTRIES.filter(({ source }) => guardWiring(source).windowError).length,
|
|
}
|
|
assert.ok(present.vueErrorHandler >= 1, 'app.config.errorHandler 全树 0 处——评审那条缺陷没修上')
|
|
assert.ok(present.rejection >= 1, 'unhandledrejection 全树 0 处')
|
|
assert.ok(present.windowError >= 1, '顶层 error 出口全树 0 处')
|
|
// 非零对照:证明扫描器真的会数东西,而不是扫了个空
|
|
const routerOnError = ENTRIES.filter(({ source }) => /router\.onError\(/.test(source)).length
|
|
assert.equal(routerOnError, 1, `router.onError 对照面应为 1 处,实测 ${routerOnError}——扫描口径变了`)
|
|
assert.ok(ENTRIES.length > 100, `只扫到 ${ENTRIES.length} 个源文件,分母不对`)
|
|
})
|
|
|
|
test('注入自证:把装配删掉,接线判据立刻变红', () => {
|
|
const main = read('src/main.ts')
|
|
assert.ok(/installGlobalErrorGuard\(\s*app\s*,/.test(main), 'main.ts 的装配形状变了,判据要跟着改')
|
|
const stripped = main.replace(/installGlobalErrorGuard\([\s\S]*?\n\}\)/, '/* 装配被删掉 */')
|
|
assert.notEqual(stripped, main, '注入没生效,这条自证是假的')
|
|
assert.ok(!/installGlobalErrorGuard\(\s*app\s*,/.test(stripped), '删掉装配后仍判成"已装",上面那条就是恒绿')
|
|
assert.ok(!/onBeforeUnmount\(\(\)\s*=>\s*\{[^}]*disposeGlobalErrorGuard\(\)/.test(
|
|
read('src/App.vue').replace('disposeGlobalErrorGuard()', '/* 卸载被删掉 */')), '卸载判据删掉了装配也照样绿')
|
|
// 真装了的那份源码必须能被同口径认出来
|
|
assert.deepEqual(guardWiring(read('src/shared/utils/app-error.ts')).vueErrorHandler, true, 'app-error.ts 里的赋值没被判成已装')
|
|
assert.deepEqual(guardWiring(read('src/shared/utils/app-error.ts')).rejection, true, 'unhandledrejection 注册没被认出')
|
|
})
|
|
|
|
test('disposeGlobalErrorGuard 走的是同一条卸载路(App.vue 里调的是它)', () => {
|
|
const world = makeWorld()
|
|
assert.deepEqual(world.listenerTypes(), ['error', 'unhandledrejection'])
|
|
disposeGlobalErrorGuard()
|
|
assert.deepEqual(world.listenerTypes(), [], 'disposeGlobalErrorGuard 没摘掉监听')
|
|
})
|