dsh-message-actions 0.2.3 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/http.cjs CHANGED
@@ -118,6 +118,41 @@ async function readJsonBody(req, res) {
118
118
  }
119
119
  }
120
120
 
121
+ /**
122
+ * 路由处理器兜底:任何未预期的异常都收敛为 500 JSON,不让 rejection 穿透到宿主 webServer。
123
+ * 流式响应已写出头部时不能再发 JSON,直接销毁连接(客户端会拿到网络错误而不是半截数据)。
124
+ *
125
+ * @param handler 原始请求处理器
126
+ * @param options { label?: string, log?: (message: string) => void }
127
+ */
128
+ function guardedHandler(handler, options) {
129
+ const o = options || {};
130
+ const label = typeof o.label === 'string' && o.label !== '' ? o.label : 'request';
131
+ const log = typeof o.log === 'function' ? o.log : null;
132
+ return async function guarded(req, res) {
133
+ try {
134
+ await handler(req, res);
135
+ } catch (err) {
136
+ if (log) {
137
+ try {
138
+ log(`[dsh-message-actions] ${label} failed: ${err instanceof Error ? err.message : String(err)}`);
139
+ } catch {
140
+ /* 日志本身失败不能影响响应 */
141
+ }
142
+ }
143
+ if (res.headersSent) {
144
+ try { res.destroy(); } catch { /* 已断开 */ }
145
+ return;
146
+ }
147
+ try {
148
+ sendError(res, 500, 'INTERNAL');
149
+ } catch {
150
+ /* 连接已断开 */
151
+ }
152
+ }
153
+ };
154
+ }
155
+
121
156
  module.exports = {
122
157
  jsonHeaders,
123
158
  sendJson,
@@ -127,5 +162,6 @@ module.exports = {
127
162
  sendBadRequest,
128
163
  sendForbidden,
129
164
  sendMethodNotAllowed,
130
- readJsonBody
165
+ readJsonBody,
166
+ guardedHandler
131
167
  };