2024-07-15 00:30:33 +08:00
|
|
|
import { Provide } from '@midwayjs/core';
|
2024-12-25 23:20:07 +08:00
|
|
|
import { IMidwayKoaContext, IWebMiddleware, NextFunction } from '@midwayjs/koa';
|
2024-11-04 16:39:02 +08:00
|
|
|
import { logger } from '@certd/basic';
|
2024-12-25 23:20:07 +08:00
|
|
|
import { Result } 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();
|
|
|
|
|
logger.info('请求开始:', url);
|
|
|
|
|
try {
|
|
|
|
|
await next();
|
2024-08-14 21:24:12 +08:00
|
|
|
logger.info('请求完成:', url, Date.now() - startTime + 'ms');
|
2023-01-29 15:26:58 +08:00
|
|
|
} catch (err) {
|
2024-12-25 23:20:07 +08:00
|
|
|
logger.error('请求异常:', url, Date.now() - startTime + 'ms', err);
|
2023-01-29 15:26:58 +08:00
|
|
|
ctx.status = 200;
|
2023-06-25 15:30:18 +08:00
|
|
|
if (err.code == null || typeof err.code !== 'number') {
|
|
|
|
|
err.code = 1;
|
|
|
|
|
}
|
|
|
|
|
ctx.body = Result.error(err.code, err.message);
|
2023-01-29 15:26:58 +08:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|