Files
37duAutomation/desktop/controlplane-next/server/src/modules/center/middleware/api-error.ts
T
puddy f27639777f build(desktop): 升级 electron-shell 版本至 1.6.3 并调整插件执行超时配置
- 插件执行超时默认延长至 6 小时,支持插件单独配置超时时间
- 新增插件根目录迁移逻辑,解决旧版权限问题
- 新增多个服务端实体、DTO、配置模块等基础代码
- 新增插件 UI 模板及相关静态资源
2026-10-15 11:38:45 +08:00

40 lines
1.6 KiB
TypeScript
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.
import { Middleware } from '@midwayjs/core';
import { Context, NextFunction } from '@midwayjs/koa';
import { IMiddleware } from '@midwayjs/core';
/**
* 全局错误兜底中间件(37du 定制):
* - /api/* 与 /auth/exchange:渲染 FastAPI 兼容的 `{"detail": "<消息>"}`(壳子/插件/agent_cli 依赖)
* - 其余路径(/admin/* 等):渲染 cool-admin 信封 `{"code": <状态码>, "message": "..."}`
*
* 关键职责:兜住一切未捕获异常(含框架对未匹配路由抛出的 404 NotFoundError),
* 不允许任何错误击穿中间件链导致进程崩溃(Node 24 下 unhandled rejection 会直接退出)。
*/
@Middleware()
export class ApiErrorMiddleware implements IMiddleware<Context, NextFunction> {
resolve() {
return async (ctx: Context, next: NextFunction) => {
try {
await next();
} catch (err: any) {
const url = (ctx.url || '').split('?')[0];
let status = Number(err?.status || err?.statusCode || 0);
// 框架 404 NotFoundError:err.code === '404'
if (!status && String(err?.code) === '404') status = 404;
const code = status >= 400 && status <= 599 ? status : 500;
const message = String(err?.message || err?.detail || '服务器内部错误');
const isDetailContract =
url.startsWith('/api/') || url === '/auth/exchange';
ctx.status = code;
if (isDetailContract) {
ctx.body = { detail: message };
} else {
ctx.body = { code: status || code, message };
}
ctx.set('Content-Type', 'application/json');
}
};
}
}