feat(dacli): client.diagnoseError() 主动诊断 + callWithDiagnosis 包装 (P0.2)
把 JNPF 模糊错误 (Database exception / Encoding cannot be repeated / Table not exists / Duplicate column name 'f_description' 等) 翻译成 具体可能原因 + 修复建议, 解决 ai-error-analysis §C 同报错 10 种根因. 设计: - recordRequestContext: postJson/putJson 自动记录 body.enCode/table/tableName - diagnoseError(msg, ctx): 纯函数, 6 类规则, 覆盖 80% 常见模糊错误 - callWithDiagnosis(fn, ctx): 包装方法, catch 时 log.warn 打诊断后 rethrow - form/dm create 已接入 (上一轮 P1.2 已 wiring, 此轮补 client 端实现) 衔接 P0.1 (loadAppContext) + P1.2 (pre-check): 不重复拉取, 不阻断主流程 (context 加载失败时 callWithDiagnosis 仍 rethrow, 不吞错)
This commit is contained in:
1 parent
95f78e6bc5
commit
ac2d5ab4ff
1 file changed
+179
-1
+179
-1
@@ -9,7 +9,7 @@
|
||||
import { encryptPassword, isEncrypted } from './crypto.ts'
|
||||
import { loadToken, saveToken, baseUrlCandidates } from './config.ts'
|
||||
import { DacliError } from './types.ts'
|
||||
import type { JnpfResp, LoginResp, TokenFile } from './types.ts'
|
||||
import type { AppContext, FormSummary, JnpfResp, LoginResp, TokenFile } from './types.ts'
|
||||
import { log } from './log.ts'
|
||||
|
||||
export interface ClientOptions {
|
||||
@@ -30,6 +30,13 @@ export class JnpfClient {
|
||||
/** 业务库 id, login 后自动拉 */
|
||||
dbLinkId?: string
|
||||
|
||||
/**
|
||||
* 最近一次请求 body 中的 enCode / table / tableName, 供 diagnoseError 用
|
||||
* 多并发不安全 (单请求场景 OK); 不入 persist (运行时状态)
|
||||
*/
|
||||
private lastRequestEnCode: string = ''
|
||||
private lastRequestTableName: string = ''
|
||||
|
||||
constructor(opt: ClientOptions = {}) {
|
||||
this.baseUrl = (opt.baseUrl || '').replace(/\/+$/, '')
|
||||
this.appCode = opt.appCode || ''
|
||||
@@ -151,6 +158,7 @@ export class JnpfClient {
|
||||
|
||||
async postJson<T = unknown>(path: string, body: unknown): Promise<JnpfResp<T>> {
|
||||
log.debug('POST', this.baseUrl + path)
|
||||
this.recordRequestContext(body)
|
||||
const res = await fetch(`${this.baseUrl}${path}`, {
|
||||
method: 'POST',
|
||||
headers: this.headers(),
|
||||
@@ -161,6 +169,7 @@ export class JnpfClient {
|
||||
|
||||
async putJson<T = unknown>(path: string, body: unknown): Promise<JnpfResp<T>> {
|
||||
log.debug('PUT', this.baseUrl + path)
|
||||
this.recordRequestContext(body)
|
||||
const res = await fetch(`${this.baseUrl}${path}`, {
|
||||
method: 'PUT',
|
||||
headers: this.headers(),
|
||||
@@ -184,6 +193,175 @@ export class JnpfClient {
|
||||
return r.data as T
|
||||
}
|
||||
|
||||
// ----- P0.2 主动诊断 (client 层 catch 时调用) -----
|
||||
|
||||
/**
|
||||
* 从请求 body 里提取 enCode / table / tableName, 供 diagnoseError 用
|
||||
* 规则: enCode 字段、表名(table / tableInfo.table / newTable) 字段
|
||||
*/
|
||||
private recordRequestContext(body: unknown): void {
|
||||
if (typeof body !== 'object' || body === null) return
|
||||
const b = body as Record<string, unknown>
|
||||
if (typeof b.enCode === 'string' && b.enCode) this.lastRequestEnCode = b.enCode
|
||||
if (typeof b.table === 'string' && b.table) this.lastRequestTableName = b.table
|
||||
if (typeof b.tableName === 'string' && b.tableName) this.lastRequestTableName = b.tableName
|
||||
// dm create body: { tableInfo: { table, newTable, tableName }, tableFieldList: [...] }
|
||||
const ti = b.tableInfo as Record<string, unknown> | undefined
|
||||
if (ti && typeof ti === 'object') {
|
||||
if (typeof ti.table === 'string' && ti.table) this.lastRequestTableName = ti.table
|
||||
if (typeof ti.newTable === 'string' && ti.newTable) this.lastRequestTableName = ti.newTable
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 主动诊断: 把 JNPF 模糊错误翻译成可能原因列表 (P0.2, 详见 doc/ai-optimization-plan.md §2.2)
|
||||
*
|
||||
* 设计:
|
||||
* - 纯函数 (无副作用, 不发请求), 仅依赖 context + lastRequestEnCode / lastRequestTableName
|
||||
* - 覆盖 doc/ai-error-analysis.md §C 列举的"同一报错 10 种根因"
|
||||
* - 返回 causes: string[], 调用方负责 log.warn 输出 (便于 AI 解析)
|
||||
* - 兜底: 未识别错误时给出"跑 context 看环境 + 看后端日志"指引
|
||||
*/
|
||||
diagnoseError(errorMsg: string, context: AppContext): string[] {
|
||||
const causes: string[] = []
|
||||
|
||||
// 规则 1: Database exception (盲点 48 — JNPF 把所有 DB 异常都包成这串)
|
||||
if (/Database exception/i.test(errorMsg)) {
|
||||
if (!context.dbLinkId || context.dbLinkId === '0') {
|
||||
causes.push(
|
||||
`dbLinkId 未设置或为 0 (当前 token.dbLinkId="${context.dbLinkId || '(空)'}").` +
|
||||
` 修复: dacli app login 重新登录自动识别业务库, 或显式 --dbLinkId=<非0 id>`,
|
||||
)
|
||||
}
|
||||
if (this.lastRequestEnCode && context.existingEnCodes?.includes(this.lastRequestEnCode)) {
|
||||
causes.push(
|
||||
`enCode "${this.lastRequestEnCode}" 已存在 (context 已记录 ${context.existingEnCodes.length} 个 enCode).` +
|
||||
` 修复: 改名加 _v2 后缀, 或 dacli form clone 已存在表单, 或 dacli form delete 后重建`,
|
||||
)
|
||||
}
|
||||
if (
|
||||
this.lastRequestTableName &&
|
||||
context.existingTables &&
|
||||
!context.existingTables.includes(this.lastRequestTableName)
|
||||
) {
|
||||
causes.push(
|
||||
`表 "${this.lastRequestTableName}" 不存在 (context 已记录 ${context.existingTables.length} 张表).` +
|
||||
` 修复: dacli dm create --table=${this.lastRequestTableName} --tableName="中文名" --dbLinkId=<id> --fields='[...]' 先建表`,
|
||||
)
|
||||
}
|
||||
if (causes.length === 0) {
|
||||
causes.push('未识别 Database exception 根因, 建议:')
|
||||
causes.push(' 1. dacli app context --json 确认环境快照')
|
||||
causes.push(' 2. 检查 tables 字段是否完整 (useBtnPermission / useFormPermission / useDataPermission)')
|
||||
causes.push(' 3. 检查 category 字段是否匹配业务库分类')
|
||||
causes.push(' 4. dacli tool logs --level=error --lines=50 看后端真实堆栈')
|
||||
}
|
||||
return causes
|
||||
}
|
||||
|
||||
// 规则 2: Encoding cannot be repeated (盲点 49)
|
||||
if (/Encoding cannot be repeated/i.test(errorMsg)) {
|
||||
if (this.lastRequestEnCode) {
|
||||
causes.push(`enCode "${this.lastRequestEnCode}" 已存在.`)
|
||||
} else {
|
||||
causes.push('enCode 重复.')
|
||||
}
|
||||
causes.push(
|
||||
' 修复: 改名加 _v2 后缀, 或 dacli form clone 已存在表单, 或 dacli form delete 后重建',
|
||||
)
|
||||
return causes
|
||||
}
|
||||
|
||||
// 规则 3: 表不存在 (dm create 误用 / form create 引不存在的表)
|
||||
if (/table.*not.*exist|TableNotFound|does not exist/i.test(errorMsg)) {
|
||||
if (this.lastRequestTableName) {
|
||||
causes.push(`表 "${this.lastRequestTableName}" 不存在.`)
|
||||
causes.push(
|
||||
` 修复: dacli dm create --table=${this.lastRequestTableName} --tableName="中文名" --dbLinkId=<id> --fields='[...]' 先建表`,
|
||||
)
|
||||
} else {
|
||||
causes.push('请求引用的表不存在.')
|
||||
causes.push(' 修复: 跑 dacli app context --json 看现有表名, 或 dacli dm list 看完整列表')
|
||||
}
|
||||
return causes
|
||||
}
|
||||
|
||||
// 规则 4: 表已存在 (dm create 重名)
|
||||
if (/Table already exists|table.*exist/i.test(errorMsg) && /create/i.test(errorMsg)) {
|
||||
causes.push(`表 "${this.lastRequestTableName || '(未知)'}" 已存在.`)
|
||||
causes.push(' 修复: 换表名, 或 dacli dm drop 后重建 (破坏性, 慎用)')
|
||||
return causes
|
||||
}
|
||||
|
||||
// 规则 5: 主键冲突 / Duplicate column name (盲点 38 — f_description 重复)
|
||||
if (/Duplicate entry|duplicate key/i.test(errorMsg)) {
|
||||
causes.push('主键冲突.')
|
||||
causes.push(' 修复: 检查数据是否已存在, 或换 ID')
|
||||
return causes
|
||||
}
|
||||
if (/Duplicate column name/i.test(errorMsg)) {
|
||||
const m = errorMsg.match(/Duplicate column name '([^']+)'/)
|
||||
const col = m?.[1] || '(未知)'
|
||||
if (col === 'f_description') {
|
||||
causes.push(`列 ${col} 已被系统自动注入为 "描述(text)" 列, 用户不应再传.`)
|
||||
causes.push(' 修复: 移除 --fields 里的 f_description, 或改名为 f_desc')
|
||||
} else {
|
||||
causes.push(`列 ${col} 重复.`)
|
||||
causes.push(' 修复: 检查 --fields 是否含与系统列同名的字段')
|
||||
}
|
||||
return causes
|
||||
}
|
||||
|
||||
// 规则 6: workflow form 缺 f_flow_task_id 列 (盲点 15)
|
||||
if (/f_flow_task_id|flowTaskId/i.test(errorMsg)) {
|
||||
causes.push('enableFlow=1 表必须含 f_flow_task_id / f_flow_id / f_flow_state 列.')
|
||||
causes.push(
|
||||
' 修复: dacli v10.6+ 自动补 9 系统列; 确认 dacli 版本, 或手动 ALTER TABLE 添加',
|
||||
)
|
||||
return causes
|
||||
}
|
||||
|
||||
// 兜底
|
||||
causes.push(`未识别的错误: ${errorMsg.slice(0, 200)}`)
|
||||
causes.push(' 建议: 跑 dacli app context --json 确认环境, 或 dacli tool logs --level=error --lines=50 看后端日志')
|
||||
return causes
|
||||
}
|
||||
|
||||
/**
|
||||
* 包装方法: 执行 + 自动诊断
|
||||
* 调用方: form/dm create 等需要在出错时给 AI 友好诊断的命令
|
||||
*
|
||||
* 行为:
|
||||
* - 正常路径: 直接透传结果
|
||||
* - 异常路径: log.warn 打诊断, 然后 rethrow (不吞错)
|
||||
* - context=null: 只 log.warn 错误信息 + "无 AppContext" 提示, 不打诊断
|
||||
*
|
||||
* 用法:
|
||||
* const ctx = await loadAppContext().catch(() => null)
|
||||
* try {
|
||||
* const r = await c.callWithDiagnosis(() => c.postJson('/visualdev/Base', body), ctx)
|
||||
* } catch (e) { process.exit(1) }
|
||||
*/
|
||||
async callWithDiagnosis<T>(
|
||||
fn: () => Promise<JnpfResp<T>>,
|
||||
context: AppContext | null,
|
||||
): Promise<JnpfResp<T>> {
|
||||
try {
|
||||
return await fn()
|
||||
} catch (e) {
|
||||
const err = e as Error
|
||||
log.warn(`! 诊断: ${err.message}`)
|
||||
if (context) {
|
||||
const causes = this.diagnoseError(err.message, context)
|
||||
log.warn(' 可能原因:')
|
||||
for (const c of causes) log.warn(` ${c}`)
|
||||
} else {
|
||||
log.warn(' (无 AppContext, 建议先跑 dacli app context --json)')
|
||||
}
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
private headers(): Record<string, string> {
|
||||
return {
|
||||
'Content-Type': 'application/json',
|
||||
|
||||
Reference in new issue
Block a user