fix: async route rejection crashes process - global async error wrap + email dup check

- users.js: check email uniqueness before insert (was ER_DUP_ENTRY uncaught crash)
- server.js: wrapAsyncRouter - Express 4 doesn't catch async handler rejections,
  route throws now go to error middleware (500 JSON) instead of uncaughtException
This commit is contained in:
2026-08-17 01:03:45 +08:00
parent 7e203d9a27
commit 42d4cafedd
2 changed files with 43 additions and 0 deletions

View File

@@ -131,11 +131,53 @@ function loadBusinessRoutes() {
businessRouter.use('/external', require('./routes/external'));
businessRouter.get('/verify', (req, res) => res.redirect(`/#/verify?token=${req.query.token}`));
wrapAsyncRouter(businessRouter);
}
if (isInstalled()) loadBusinessRoutes();
global.__loadBusinessRoutes = loadBusinessRoutes;
// Express 4 不自动捕获 async handler 的 rejection, 一旦 Promise 拒绝会 uncaughtException 崩掉整个进程。
// 对所有已挂载路由做递归包装: rejection → next(err) → 统一错误中间件(500 JSON)。
function wrapAsyncRouter(router) {
if (!router || router.__asyncWrapped) return;
router.__asyncWrapped = true;
for (const layer of router.stack) {
if (layer.route) {
for (const rl of layer.route.stack) {
const h = rl.handle;
if (typeof h === 'function' && h.length <= 3) {
rl.handle = (req, res, next) => {
try { const p = h(req, res, next); if (p && p.catch) p.catch(next); } catch (e) { next(e); }
};
}
}
} else {
const h = layer.handle;
if (typeof h === 'function' && h.stack) { wrapAsyncRouter(h); continue; }
if (typeof h === 'function' && h.length <= 3) {
layer.handle = (req, res, next) => {
try { const p = h(req, res, next); if (p && p.catch) p.catch(next); } catch (e) { next(e); }
};
}
}
}
}
wrapAsyncRouter(businessRouter);
wrapAsyncRouter(installRoutes);
// 顶层 async 路由同样包装
for (const layer of app._router.stack) {
if (layer.route && layer.route.path === '/' && layer.route.stack[0]) {
const h = layer.route.stack[0].handle;
if (typeof h === 'function' && h.length <= 3) {
layer.route.stack[0].handle = (req, res, next) => {
try { const p = h(req, res, next); if (p && p.catch) p.catch(next); } catch (e) { next(e); }
};
}
}
}
app.get('/api/health', (req, res) => res.json({ status: 'ok', installed: isInstalled() }));
app.get('/', async (req, res) => {