2026-05-31 01:41:33 +08:00
|
|
|
import { Provide } from "@midwayjs/core";
|
|
|
|
|
import { IMidwayKoaContext, IWebMiddleware, NextFunction } from "@midwayjs/koa";
|
|
|
|
|
import { logger } from "@certd/basic";
|
2025-04-17 22:34:21 +08:00
|
|
|
import { Result, TextException } from "@certd/lib-server";
|
2023-01-29 15:26:58 +08:00
|
|
|
|
|
|
|
|
@Provide()
|
|
|
|
|
export class GlobalExceptionMiddleware implements IWebMiddleware {
|
|
|
|
|
resolve() {
|
|
|
|
|
return async (ctx: IMidwayKoaContext, next: NextFunction) => {
|
|
|
|
|
const { url } = ctx;
|
|
|
|
|
const startTime = Date.now();
|
2026-05-31 01:41:33 +08:00
|
|
|
logger.info("请求开始:", url);
|
2023-01-29 15:26:58 +08:00
|
|
|
try {
|
|
|
|
|
await next();
|
2026-05-31 01:41:33 +08:00
|
|
|
logger.info("请求完成:", url, Date.now() - startTime + "ms");
|
2023-01-29 15:26:58 +08:00
|
|
|
} catch (err) {
|
2026-05-31 01:41:33 +08:00
|
|
|
if (err instanceof TextException) {
|
|
|
|
|
delete err.stack;
|
2025-04-17 22:34:21 +08:00
|
|
|
}
|
2026-05-31 01:41:33 +08:00
|
|
|
logger.error("请求异常:", url, Date.now() - startTime + "ms", err);
|
2023-01-29 15:26:58 +08:00
|
|
|
ctx.status = 200;
|
2026-05-31 01:41:33 +08:00
|
|
|
if (err.code == null || typeof err.code !== "number") {
|
2023-06-25 15:30:18 +08:00
|
|
|
err.code = 1;
|
|
|
|
|
}
|
2026-05-31 01:41:33 +08:00
|
|
|
ctx.body = Result.error(err.code, err.message, err.data);
|
2023-01-29 15:26:58 +08:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|