packServer/backend/app/middleware/error_handler.js
liufumingren 8949b7198c feat(pay): 微信 Native 扫码支付(下单出码 + 回调入账 + 扫码轮询)
- 新增 service/wxpay.js:统一下单 / 查询订单 / 关闭订单 / APIv2 验签,二维码在服务端本地生成 SVG
- 新增 pay/wechat.js 与 XML 编解码,公开回调 POST /api/pay/wechat/notify
- 订单:同主体 + 同套餐复用未超时待支付单;2 小时超时关单;回调 / 查单 / 手工确认统一走 payNotify
- 迁移 subject_orders 增加 code_url / prepay_id 等字段,配置项 WXPAY_*
- 前端续期弹窗展示二维码并按 2s 轮询支付结果
- 文档与测试同步更新

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-07 16:23:03 +08:00

55 lines
2.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/**
* 统一错误处理(后端不再渲染页面 → 只会返回 JSON 或纯文本)
*
* - 接口请求(`/api/*`、`/health` 或声明了 Accept: application/json)→ `{ ok:false, message }`
* - 其它请求(正常都被 app/middleware/frontend.js 接走了)→ 一行纯文本
*
* 4xx 返回原始消息,5xx 只对外返回「服务器内部错误」并记入 common-error.log。
*/
module.exports = () => {
return async function errorHandler(ctx, next) {
try {
await next();
// 没匹配到任何路由的接口请求:框架/koa 默认回 HTML 404(客户端按 JSON 解析会报
// `Unexpected token '<'`),这里统一成 JSON —— 控制器自己给的 404(对象 body)不动
// ⚠️ 给 ctx.body 赋值会把「默认的 404」顶成 200,所以必须显式把状态码钉回 404
const isApiPath = ctx.path.startsWith('/api/') || ctx.path === '/health';
if (ctx.status === 404 && isApiPath && !(ctx.body && typeof ctx.body === 'object')) {
ctx.body = { ok: false, message: '接口不存在' };
ctx.status = 404;
}
} catch (err) {
const status = err.status >= 400 && err.status < 600 ? err.status : 500;
if (status >= 500) {
// 交给框架的 onerror 记录日志(common-error.log)
ctx.app.emit('error', err, ctx);
} else {
ctx.logger.warn('[http] %s %s -> %s %s', ctx.method, ctx.url, status, err.message);
}
// 响应已经开始发送(例如已反代出去 / 流式输出)时不能再改 body
if (ctx.headerSent) return;
// 5xx 默认不外传细节;显式标了 `expose` 的(例如「微信支付:签名错误」这类
// 需要运维照着改配置的)才把原始消息透出去
const message = status >= 500 && !err.expose ? '服务器内部错误' : err.message;
// 接口请求返回 JSON,其它(理论上都被 frontend 中间件接走了)返回纯文本
const isApi = ctx.path.startsWith('/api/') || ctx.path === '/health' || ctx.acceptJSON;
ctx.status = status;
if (isApi) {
ctx.body = { ok: false, message };
return;
}
ctx.type = 'text/plain; charset=utf-8';
ctx.body = `${status} ${message}`;
}
};
};