Files
competition-website/unit_auth_catch.cjs
WorkBuddy a303cf2d53 chore: 后端首次基线提交
运行必须源码:app/(controller/model/service/middleware/lib/utils/validate/router)、config/、database/(migrations/seeders/sql)、启动脚本、app/public/templates 模板。
已忽略运行非必须:node_modules/、logs/、run/、app/public 运行时上传数据、.env*、构建/缓存产物。
2026-08-17 12:25:42 +08:00

19 lines
862 B
JavaScript

const jwt = require('jsonwebtoken');
const authFactory = require('./app/middleware/auth.js');
const SECRET = 'unit-test-secret';
const token = jwt.sign({ id: 1, role: 'contestant' }, SECRET);
function makeCtx() {
return { get: (h) => (h === 'Authorization' ? 'Bearer ' + token : ''),
status: 200, body: null, state: {},
app: { config: { jwt: { secret: SECRET } } } };
}
const throwingNext = async () => { throw new Error('EACCES: readdirSync failed'); };
const mw = authFactory({}, { config: { jwt: { secret: SECRET } } });
(async () => {
try { await mw(makeCtx(), throwingNext); console.log('RESULT: 未抛错(不应发生)'); }
catch (e) {
console.log('RESULT: 中间件重新抛出异常 ->', e.message);
console.log('=> 异常被 Egg 全局错误处理为 500+日志,【不会】再被伪装成 401「认证失败」');
}
})();