/** * Envelope errors stay on stable reasons. Server message text must not surface. */ import { describe, expect, it } from "vitest"; import { BusinessError } from "@watchman/api"; import { describeAlarmError, isAlarmConflict, isAlarmNotFound } from "./errors"; const MESSAGES: Record = { "alarm.errors.already_claimed": "已经有处理人", "alarm.errors.forbidden": "没有权限({node})", "alarm.errors.forbiddenPlain": "没有权限完成这个操作", "codes.40000": "参数错误", "codes.42000": "权限不足", "alarm.list.loadFailed": "报警列表加载失败", }; const t = (key: string, named?: Record) => { const template = MESSAGES[key] ?? key; if (!named) { return template; } return template.replace(/\{(\w+)\}/g, (_match, name: string) => String(named[name] ?? "")); }; const te = (key: string) => key in MESSAGES; function business( code: number, status: number, details: Record = {}, message = "SECRET server text", ): BusinessError { return new BusinessError({ code, message, details, status, requestId: "r" }); } describe("describeAlarmError", () => { it("uses the stable reason and hides the server message", () => { const text = describeAlarmError( business(40000, 409, { reason: "already_claimed" }), t, te, "alarm.list.loadFailed", ); expect(text).toBe("已经有处理人"); expect(text).not.toContain("SECRET"); }); it("shows the permission node we already know, not the server message", () => { const text = describeAlarmError( business(42000, 403, {}, "raw denial"), t, te, "alarm.list.loadFailed", "perm:data:emp:watchman.alarm.take", ); expect(text).toBe("没有权限(perm:data:emp:watchman.alarm.take)"); expect(text).not.toContain("raw denial"); }); it("falls back to the numeric code, then to the fallback, without the thrown text", () => { expect(describeAlarmError(business(40000, 400, { reason: "unheard" }), t, te, "alarm.list.loadFailed")).toBe( "参数错误 (40000)", ); expect(describeAlarmError(business(50000, 500), t, te, "alarm.list.loadFailed")).toBe( "报警列表加载失败 (50000)", ); expect(describeAlarmError(new Error("SECRET network"), t, te, "alarm.list.loadFailed")).toBe( "报警列表加载失败", ); }); }); describe("alarm error status", () => { it("treats HTTP 404 as not found and HTTP 409 as conflict", () => { expect(isAlarmNotFound(business(40000, 404, { reason: "not_found" }))).toBe(true); expect(isAlarmNotFound(business(40000, 400))).toBe(false); expect(isAlarmConflict(business(40000, 409, { reason: "already_claimed" }))).toBe(true); expect(isAlarmConflict(business(40000, 400))).toBe(false); }); });