Files
uncle6me-web 11e772496f fix(t75 ①): portal 不再把 JSON 解析錯誤噴給使用者+404 說人話
leo 同事實測:存 Gemini 金鑰時畫面出現
「Unexpected non-whitespace character after JSON at position 4」。

根因兩層:
① 前端 15 處無條件 r.json(),但伺服器不一定回 JSON——404 頁/CF 錯誤頁都是 HTML。
   JSON.parse 一爆,錯誤沿 .catch 走到 friendlyErr,而 friendlyErr 最後一行是
    =把任何例外訊息原樣顯示 ⇒ 技術英文直接噴到畫面。
② 真正的原因是 /portal/admin/chat-key 回 404(實例的 cypher 是舊版沒這端點),
   但使用者完全看不出來,只看到一句看不懂的英文。

修:
- 新增 safeJson(r):用 r.text() 再 try/catch parse,解析不了回 {} 不拋錯;15 處改用它
- friendlyErr 收斂:JSON 類錯誤→「伺服器回應異常,請稍後再試」;
  純英文技術訊息→「操作失敗」;我們自己寫的中文訊息才原樣顯示
- 兩處金鑰儲存加 404 專屬提示:「你的知識庫版本還沒有這個功能,請先更新知識庫」
  ——講清楚為什麼與怎麼辦,否則他只看到「儲存失敗」會反覆重試同一件事
- 順手:安裝卡片那處原本 x.d.error 在 x.d 為 undefined 時會再爆一次,補 x.d && 防護

測試 safejson.test.mjs 8/8:404 HTML 不拋錯/空回應/正常 JSON 仍解析得出/
JSON 錯誤不外洩原文且說人話/網路錯誤訊息保留/中文訊息原樣/英文技術訊息收斂。

⚠️ 這只解「不噴技術訊息」;金鑰要真的存得進去仍需實例更新 cypher(②層待辦)。
2026-07-28 01:02:12 +08:00

47 lines
2.4 KiB
JavaScript

import fs from 'node:fs';
const html = fs.readFileSync(new URL('./index.html', import.meta.url).pathname,'utf8');
// 抽出 safeJson 與 friendlyErr 求值
const grab = (name) => {
const i = html.indexOf(`function ${name}(`);
if (i < 0) throw new Error(`找不到 ${name}`);
let d=0, j=html.indexOf('{', i);
for (let k=j;k<html.length;k++){ if(html[k]==='{')d++; if(html[k]==='}'){d--; if(!d){ return html.slice(i,k+1);} } }
throw new Error('括號不平衡');
};
const fn = new Function(grab('safeJson') + '\n' + grab('friendlyErr') + '\nreturn {safeJson, friendlyErr};')();
let pass=0, fail=0;
const t=(l,c,e='')=>{c?(console.log('PASS:',l),pass++):(console.log('FAIL:',l,e),fail++)};
// ① safeJson:非 JSON 不可拋例外(同事撞到的 404 HTML 頁)
const html404 = '<!DOCTYPE html><html><body>404 Not Found</body></html>';
await fn.safeJson({ text: () => Promise.resolve(html404) })
.then(d => t('404 HTML → 回空物件不拋錯', typeof d === 'object' && d !== null))
.catch(e => t('404 HTML → 不該拋錯', false, e.message));
await fn.safeJson({ text: () => Promise.resolve('') })
.then(d => t('空回應 → 回空物件', JSON.stringify(d)==='{}'))
.catch(() => t('空回應 → 不該拋錯', false));
await fn.safeJson({ text: () => Promise.resolve('{"error":"帳號或密碼不對"}') })
.then(d => t('正常 JSON 仍要解析得出來', d.error === '帳號或密碼不對'), )
.catch(() => t('正常 JSON 不該拋錯', false));
// ② friendlyErr:不可把技術訊息噴給使用者
const leak = fn.friendlyErr(new Error('Unexpected non-whitespace character after JSON at position 4'));
t('JSON 錯誤 → 不外洩原文', !/JSON|position/i.test(leak), `實得: ${leak}`);
t('JSON 錯誤 → 說人話', /伺服器回應異常/.test(leak), `實得: ${leak}`);
const net = fn.friendlyErr(new Error('Failed to fetch'));
t('網路錯誤 → 既有訊息保留', /連線中斷/.test(net), `實得: ${net}`);
const ours = fn.friendlyErr(new Error('帳號或密碼不對——用你在知識庫網站設定的那組'));
t('我們自己的中文訊息 → 原樣顯示', /帳號或密碼不對/.test(ours), `實得: ${ours}`);
const stack = fn.friendlyErr(new Error('TypeError: Cannot read properties of undefined'));
t('英文技術訊息 → 收斂不外洩', !/TypeError|undefined/.test(stack), `實得: ${stack}`);
console.log(`\n=== ${pass} passed, ${fail} failed ===`);
process.exit(fail?1:0);