diff --git a/src/cli/errors.ts b/src/cli/errors.ts index dd0d666..ade642a 100644 --- a/src/cli/errors.ts +++ b/src/cli/errors.ts @@ -1,3 +1,5 @@ +import { EkbError } from "../core/errors.js"; + export type CliExitCode = 1 | 2 | 10 | 11 | 12; export class CliError extends Error { @@ -35,6 +37,15 @@ export function classifyCliError(error: unknown): { return { exitCode: error.exitCode, nextAction: error.nextAction }; } + if (error instanceof EkbError) { + if (error.code === "NOT_LOGGED_IN" || error.code === "AUTH_FAILED" || error.status === 401) { + return { exitCode: 11, nextAction: "hose-use auth login" }; + } + if (error.code === "VALIDATION_ERROR") { + return { exitCode: 2 }; + } + } + const value = error instanceof Error ? error.message : String(error); const status = responseStatus(error); if (status === 401 || status === 403 || /(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(value)) { @@ -56,3 +67,4 @@ function responseStatus(error: unknown): number | undefined { const status = (response as { status?: unknown }).status; return typeof status === "number" ? status : undefined; } + diff --git a/src/core/config/manager.ts b/src/core/config/manager.ts index 1d834d7..c382104 100644 --- a/src/core/config/manager.ts +++ b/src/core/config/manager.ts @@ -5,6 +5,7 @@ import { getCorpStaffId, getCorpStaffName, } from "./types.js"; +import { NotFoundError, NotLoggedInError, ValidationError } from "../errors.js"; import { saveGlobalConfig } from "./loader.js"; export interface CorpSummary { @@ -44,11 +45,11 @@ export function resolveCorpConfig( corp = corps.find((item) => getCorpPhysicalId(item) === selectedCorpId); } if (corp) return corp; - throw new Error(`未找到企业或身份标识为 [${selectedCorpId}] 的企业配置`); + throw new NotFoundError(`未找到企业或身份标识为 [${selectedCorpId}] 的企业配置`); } if (!options.stateful) { - throw new Error( + throw new ValidationError( "当前处于无状态模式 (Stateless Mode)。执行企业级操作必须显式指定 --corp 。\n" + "如需设置默认企业,可执行 `hose-use config mode stateful` 切换为有状态模式。" ); @@ -58,7 +59,7 @@ export function resolveCorpConfig( if (firstCorp) return firstCorp; const hintDirs = candidateDirs?.length ? ` (已检索路径: ${candidateDirs.join(", ")})` : ""; - throw new Error(`未找到任何企业配置。请先运行 'hose-use auth login' 登录或添加企业配置${hintDirs}。`); + throw new NotLoggedInError(`未找到任何企业配置。请先运行 'hose-use auth login' 登录或添加企业配置${hintDirs}。`); } export class CorpContext { diff --git a/src/core/errors.ts b/src/core/errors.ts index 9540110..87b5983 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -12,12 +12,35 @@ export class EkbError extends Error { export class NotLoggedInError extends EkbError { constructor(message = "No corp selected") { super(message, "NOT_LOGGED_IN", 401); + this.name = "NotLoggedInError"; } } export class AuthenticationError extends EkbError { constructor(message = "Authentication failed") { super(message, "AUTH_FAILED", 401); + this.name = "AuthenticationError"; + } +} + +export class PermissionError extends EkbError { + constructor(message = "Permission denied") { + super(message, "FORBIDDEN", 403); + this.name = "PermissionError"; + } +} + +export class NotFoundError extends EkbError { + constructor(message: string, code = "NOT_FOUND") { + super(message, code, 404); + this.name = "NotFoundError"; + } +} + +export class ValidationError extends EkbError { + constructor(message: string, code = "VALIDATION_ERROR") { + super(message, code, 400); + this.name = "ValidationError"; } } @@ -35,3 +58,4 @@ export class EkbApiError extends EkbError { } } + diff --git a/src/domains/approval/repository.ts b/src/domains/approval/repository.ts index e0a3c6e..4c68046 100644 --- a/src/domains/approval/repository.ts +++ b/src/domains/approval/repository.ts @@ -1,4 +1,5 @@ import { Database } from "bun:sqlite"; +import { BusinessError, NotFoundError } from "../../core/errors.js"; import { getApprovalDatabase } from "./db.js"; import { parseRuleBody, validatePreferenceText } from "./parser.js"; import { @@ -205,7 +206,7 @@ export class ApprovalRepository { public updateRule(id: string, updates: UpdateRuleInput): RuleRecord { const existing = this.getRuleById(id); if (!existing) { - throw new Error(`未找到 ID 为 "${id}" 的规则`); + throw new NotFoundError(`未找到 ID 为 "${id}" 的规则`); } if (updates.body !== undefined) { @@ -247,7 +248,7 @@ export class ApprovalRepository { .query("SELECT * FROM preferences ORDER BY updated_at DESC LIMIT 1") .get() as any; if (!fallback) { - throw new Error("数据库未初始化默认偏好配置"); + throw new NotFoundError("数据库未初始化默认偏好配置"); } return this.mapPreferenceRow(fallback); } @@ -266,7 +267,7 @@ export class ApprovalRepository { ): PreferenceRecord { const existing = this.getPreferenceById(id); if (!existing) { - throw new Error(`未找到 ID 为 "${id}" 的偏好配置`); + throw new NotFoundError(`未找到 ID 为 "${id}" 的偏好配置`); } if (updates.rulesReject !== undefined) validatePreferenceText(updates.rulesReject); @@ -371,7 +372,7 @@ export class ApprovalRepository { if (row) return this.mapRunRow(row); const expiredRow = this.db.query("SELECT * FROM approval_runs WHERE UPPER(short_id) = UPPER(?)").get(trimmed) as any; if (expiredRow) { - throw new Error(`审批会话 [${trimmed}] 已过期(有效时长 6 小时),请运行 hose-aipro init 重新发起审批会话`); + throw new BusinessError(`审批会话 [${trimmed}] 已过期(有效时长 6 小时),请运行 hose-aipro init 重新发起审批会话`); } } // 2. 尝试按长 UUID 查找 @@ -431,7 +432,7 @@ export class ApprovalRepository { ): ApprovalRunRecord { const existing = this.getRunById(id); if (!existing) { - throw new Error(`未找到 ID 为 "${id}" 的审批运行记录`); + throw new NotFoundError(`未找到 ID 为 "${id}" 的审批运行记录`); } const now = Date.now(); @@ -468,7 +469,7 @@ export class ApprovalRepository { public injectFindings(runId: string, findings: CreateFindingInput[]): ApprovalFindingRecord[] { const run = this.getRunById(runId); if (!run) { - throw new Error(`审批运行记录不存在: ${runId}`); + throw new NotFoundError(`审批运行记录不存在: ${runId}`); } // 重新挂载时清空旧要点 @@ -521,7 +522,7 @@ export class ApprovalRepository { ): ApprovalFindingRecord { const row = this.db.query("SELECT * FROM approval_findings WHERE id = ?").get(findingId) as any; if (!row) { - throw new Error(`未找到审核要点记录: ${findingId}`); + throw new NotFoundError(`未找到审核要点记录: ${findingId}`); } const checkStatus = updates.checkStatus ?? row.check_status; diff --git a/src/domains/approval/service.ts b/src/domains/approval/service.ts index 7f49b03..420bd0a 100644 --- a/src/domains/approval/service.ts +++ b/src/domains/approval/service.ts @@ -1,4 +1,5 @@ import { KyInstance } from "ky"; +import { BusinessError, NotFoundError } from "../../core/errors.js"; import { ApprovalRepository } from "./repository.js"; import { parseRuleBody } from "./parser.js"; import { @@ -64,7 +65,7 @@ export class ApprovalService { // 1. 获取单据详情 const bills = await getBillByCodeOrId(client, corpId, documentSn); if (bills.length === 0) { - throw new Error(`在当前企业下未找到单号或 ID 为 [${documentSn}] 的单据`); + throw new NotFoundError(`在当前企业下未找到单号或 ID 为 [${documentSn}] 的单据`); } const bill = bills[0]; const actualSn = bill.billCode || documentSn; @@ -75,7 +76,7 @@ export class ApprovalService { if (!scopeDetail) { const allScopes = this.repo.listScopes(); if (allScopes.length === 0) { - throw new Error("规约库中暂无任何生效规则,请先使用 hose-use rule add <场景> <正文> 新增规则"); + throw new BusinessError("规约库中暂无任何生效规则,请先使用 hose-use rule add <场景> <正文> 新增规则"); } // 自动启发式场景匹配 @@ -95,7 +96,7 @@ export class ApprovalService { } if (!scopeDetail || scopeDetail.rules.length === 0) { - throw new Error(`适用场景 [${options.scope ?? "自动匹配"}] 下暂无任何生效规则`); + throw new NotFoundError(`适用场景 [${options.scope ?? "自动匹配"}] 下暂无任何生效规则`); } // 3. 提取所有规则的 AST 条款要点 @@ -119,7 +120,7 @@ export class ApprovalService { } if (clauseInputs.length === 0) { - throw new Error(`场景 [${scopeDetail.scope}] 下的规则正文中未解析出任何合法判定要点 ([动作]{级别})`); + throw new BusinessError(`场景 [${scopeDetail.scope}] 下的规则正文中未解析出任何合法判定要点 ([动作]{级别})`); } // 4. 为单据创建/重置审批运行记录 @@ -192,7 +193,7 @@ export class ApprovalService { } if (!target) { - throw new Error(`未找到要点: ${item.id ?? `#${item.index}`}`); + throw new NotFoundError(`未找到要点: ${item.id ?? `#${item.index}`}`); } this.repo.updateFinding(target.id, { diff --git a/src/domains/approval/types.ts b/src/domains/approval/types.ts index d5c5313..dcd2932 100644 --- a/src/domains/approval/types.ts +++ b/src/domains/approval/types.ts @@ -107,18 +107,18 @@ export interface ApprovalFindingRecord { createdAt: number; } -export class ApprovalRuleValidationError extends Error { - public readonly code = "RULE_VALIDATION_ERROR"; +import { BusinessError } from "../../core/errors.js"; + +export class ApprovalRuleValidationError extends BusinessError { constructor(message: string) { - super(message); + super(message, "RULE_VALIDATION_ERROR", 400); this.name = "ApprovalRuleValidationError"; } } -export class ApprovalGatewayBlockedError extends Error { - public readonly code = "APPROVAL_GATEWAY_BLOCKED"; +export class ApprovalGatewayBlockedError extends BusinessError { constructor(message: string) { - super(message); + super(message, "APPROVAL_GATEWAY_BLOCKED", 400); this.name = "ApprovalGatewayBlockedError"; } } diff --git a/src/domains/bill/tools.ts b/src/domains/bill/tools.ts index 06e0384..906a2c1 100644 --- a/src/domains/bill/tools.ts +++ b/src/domains/bill/tools.ts @@ -3,6 +3,13 @@ import { existsSync } from "node:fs"; import { mkdir, writeFile } from "node:fs/promises"; import { basename, extname, join, resolve } from "node:path"; import { getGlobalCache } from "../../core/cache/index.js"; +import { + BusinessError, + EkbApiError, + NotFoundError, + PermissionError, + ValidationError, +} from "../../core/errors.js"; import { searchRawBills, getRawBillsByIds, @@ -532,13 +539,13 @@ export async function downloadBillAttachments( report: BillAttachmentReport; }> { const report = await getBillAttachments(client, corpId, target); - if (!report) throw new Error(`未找到单据附件: ${target}`); + if (!report) throw new NotFoundError(`未找到单据附件: ${target}`); const selected = fileId ? report.attachments.filter((item) => item.fileId === fileId) : report.attachments; if (fileId && selected.length === 0) { - throw new Error(`单据 ${target} 中未找到附件 fileId: ${fileId}`); + throw new NotFoundError(`单据 ${target} 中未找到附件 fileId: ${fileId}`); } const destination = resolve(outputDir); @@ -556,7 +563,7 @@ export async function downloadBillAttachments( const path = uniqueAttachmentPath(destination, safeAttachmentName(sourceName), attachment.fileId, usedPaths); const response = await fetch(attachment.url); if (!response.ok) { - throw new Error(`附件下载失败 (${response.status}): ${sourceName}`); + throw new EkbApiError(`附件下载失败 (${response.status}): ${sourceName}`, "ATTACHMENT_DOWNLOAD_FAILED", response.status); } const content = new Uint8Array(await response.arrayBuffer()); await writeFile(path, content); @@ -958,7 +965,7 @@ function actionTarget(raw: Record, fallback: string): BillActio const form = flow.form && typeof flow.form === "object" ? flow.form as Record : {}; const backlogId = typeof raw.id === "string" ? raw.id : fallback; const flowId = typeof flow.id === "string" ? flow.id : undefined; - if (!flowId) throw new Error(`未找到单据流程 ID: ${fallback}`); + if (!flowId) throw new NotFoundError(`未找到单据流程 ID: ${fallback}`); const plan = flow.plan && typeof flow.plan === "object" ? flow.plan as Record : {}; const nodes = Array.isArray(plan.nodes) ? plan.nodes : []; const nodeName = typeof raw.nodeName === "string" ? raw.nodeName : undefined; @@ -979,7 +986,7 @@ function actionTarget(raw: Record, fallback: string): BillActio async function resolveActionTarget(client: KyInstance, corpId: string, target: string): Promise { const raw = await getRawBillFlow(client, corpId, target); - if (!raw) throw new Error(`未找到单据或审批任务: ${target}`); + if (!raw) throw new NotFoundError(`未找到单据或审批任务: ${target}`); return actionTarget(raw, target); } @@ -1019,11 +1026,11 @@ export async function resolveBillStaffIds( for (const value of values) { const matches = matchesFor(value); if (matches.length !== 1) { - if (matches.length > 1) throw new Error(`员工关键词 [${value}] 匹配到多人,请改用员工 ID 或工号`); - throw new Error(`未找到员工 [${value}]`); + if (matches.length > 1) throw new ValidationError(`员工关键词 [${value}] 匹配到多人,请改用员工 ID 或工号`); + throw new NotFoundError(`未找到员工 [${value}]`); } const id = typeof matches[0]?.id === "string" ? matches[0].id : undefined; - if (!id) throw new Error(`员工 [${value}] 缺少可用 ID`); + if (!id) throw new BusinessError(`员工 [${value}] 缺少可用 ID`); result.push(id); } return result; @@ -1050,7 +1057,7 @@ async function runBillAction( const allowed = entry?.[1]; const requiredAction = action === "approve" ? "freeflow.agree" : action === "reject" ? "freeflow.reject" : "freeflow.addnode"; if (!Array.isArray(allowed) || !allowed.includes(requiredAction)) { - throw new Error(`当前账号不是该节点的合法待办人,不能执行 ${action} 动作`); + throw new PermissionError(`当前账号不是该节点的合法待办人,不能执行 ${action} 动作`); } } } @@ -1078,22 +1085,22 @@ export function approveBill(client: KyInstance, corpId: string, target: string, } export function rejectBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) { - if (!options.comment?.trim()) throw new Error("驳回原因不能为空"); + if (!options.comment?.trim()) throw new ValidationError("驳回原因不能为空"); return runBillAction(client, corpId, target, "reject", options); } export function transferBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) { - if (!options.approverIds?.length) throw new Error("转交审批至少需要一个 approverId"); + if (!options.approverIds?.length) throw new ValidationError("转交审批至少需要一个 approverId"); return runBillAction(client, corpId, target, "transfer", options); } export function addNodeBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) { - if (!options.approverIds?.length) throw new Error("加签审批至少需要一个 approverId"); + if (!options.approverIds?.length) throw new ValidationError("加签审批至少需要一个 approverId"); return runBillAction(client, corpId, target, "add-node", options); } export function commentBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) { - if (!options.comment?.trim()) throw new Error("评论内容不能为空"); + if (!options.comment?.trim()) throw new ValidationError("评论内容不能为空"); return runBillAction(client, corpId, target, "comment", options); } @@ -1268,13 +1275,15 @@ export async function searchAndFormatBills( }); } catch (err) { if (String(err).includes("timed out") || (err as any)?.name === "TimeoutError") { - throw new Error( + throw new EkbApiError( `全局单据台账检索超时。在大企业或海量单据租户中,建议指定时间范围或单号筛选:\n` + `建议:\n` + ` - 指定时间范围:hose-use bill list --since=7d 或 --start-date=2026-09-01\n` + ` - 查看当前员工发起的单据:hose-use task submitted 或 hose-use bill list --mine\n` + ` - 查看待我审批单据:hose-use task todo\n` + - ` - 按单号精确查询:hose-use bill get <单号>` + ` - 按单号精确查询:hose-use bill get <单号>`, + "BILL_SEARCH_TIMEOUT", + 504 ); } throw err; diff --git a/src/domains/platform/workflow-state.ts b/src/domains/platform/workflow-state.ts index ea03864..c418c01 100644 --- a/src/domains/platform/workflow-state.ts +++ b/src/domains/platform/workflow-state.ts @@ -1,3 +1,4 @@ +import { NotFoundError, ValidationError } from "../../core/errors.js"; import type { WorkflowDetail } from "./types.js"; export type WorkflowDraftStatus = "clean" | "dirty" | "saving" | "saved" | "failed"; @@ -19,9 +20,9 @@ function pathParts(path: string): string[] { .split(".") .map((part) => part.trim()) .filter(Boolean); - if (!parts.length) throw new Error("工作流配置路径不能为空"); + if (!parts.length) throw new ValidationError("工作流配置路径不能为空"); if (parts.some((part) => !/^[A-Za-z_$][\w$-]*$/.test(part) && !/^\d+$/.test(part))) { - throw new Error(`工作流配置路径非法: ${path}`); + throw new ValidationError(`工作流配置路径非法: ${path}`); } return parts; } @@ -40,12 +41,12 @@ export function applyWorkflowPathPatch( let cursor: any = patched; for (const part of parts.slice(0, -1)) { if (cursor === null || typeof cursor !== "object" || !(part in cursor)) { - throw new Error(`工作流配置路径不存在: ${path}`); + throw new NotFoundError(`工作流配置路径不存在: ${path}`); } cursor = cursor[part]; } if (cursor === null || typeof cursor !== "object") { - throw new Error(`工作流配置路径不可写: ${path}`); + throw new ValidationError(`工作流配置路径不可写: ${path}`); } cursor[parts.at(-1)!] = value; return patched as WorkflowDetail;