新增运行时 openPage/takePageQuery,tabBar 页自动使用 switchTab 并传递参数 - 编译器写入 tabPages,并拒绝 navigateTo/redirectTo 到 tabBar 页或 switchTab 带参数 - 阿成首页、套餐、出摊、主理人、详情、记录、成功页跳转统一改用 openPage - 套餐筛选改用后台业务提供项分类;详情跳咨询时携带业务提供项 - 移除 capability-booking:小程序无入口且依赖已删除的 /public/brand,需求由咨询表单覆盖"
62 lines
2.4 KiB
TypeScript
62 lines
2.4 KiB
TypeScript
import { Catch, HttpException, Injectable } from "@nestjs/common";
|
||
import type { ArgumentsHost, ExceptionFilter } from "@nestjs/common";
|
||
import type { FastifyReply, FastifyRequest } from "fastify";
|
||
import { randomUUID } from "node:crypto";
|
||
|
||
@Injectable()
|
||
export class RequestIdMiddleware {
|
||
use(request: FastifyRequest, reply: FastifyReply, next: () => void): void {
|
||
const requestId = request.headers["x-request-id"]?.toString() ?? randomUUID();
|
||
if (typeof reply.header === "function") {
|
||
reply.header("x-request-id", requestId);
|
||
} else {
|
||
(reply as unknown as { setHeader: (name: string, value: string) => void }).setHeader(
|
||
"x-request-id",
|
||
requestId,
|
||
);
|
||
}
|
||
(request as FastifyRequest & { requestId?: string }).requestId = requestId;
|
||
if (process.env.NODE_ENV === "development") {
|
||
console.info("api request", { method: request.method, url: request.url, requestId });
|
||
}
|
||
next();
|
||
}
|
||
}
|
||
|
||
/** HttpException.getResponse() 可能是字符串,或 { message: string | string[] }(含 ValidationPipe 错误)。 */
|
||
function readMessage(detail: unknown): string {
|
||
if (typeof detail === "string") return detail;
|
||
const message = (detail as { message?: unknown } | null)?.message;
|
||
if (typeof message === "string" && message) return message;
|
||
if (Array.isArray(message) && message.length) return message.map(String).join(";");
|
||
return "请求失败";
|
||
}
|
||
|
||
@Catch()
|
||
export class ApiExceptionFilter implements ExceptionFilter {
|
||
catch(exception: unknown, host: ArgumentsHost): void {
|
||
const context = host.switchToHttp();
|
||
const response = context.getResponse<FastifyReply>();
|
||
const request = context.getRequest<FastifyRequest>();
|
||
const status = exception instanceof HttpException ? exception.getStatus() : 500;
|
||
if (!(exception instanceof HttpException)) console.error("api unhandled error", exception);
|
||
const detail =
|
||
exception instanceof HttpException
|
||
? exception.getResponse()
|
||
: process.env.NODE_ENV === "development" && exception instanceof Error
|
||
? exception.message
|
||
: "服务器内部错误";
|
||
response.status(status).send({
|
||
data: null,
|
||
error: {
|
||
code: `HTTP_${status}`,
|
||
message: readMessage(detail),
|
||
},
|
||
requestId:
|
||
(request as FastifyRequest & { requestId?: string }).requestId ??
|
||
request.headers["x-request-id"] ??
|
||
null,
|
||
});
|
||
}
|
||
}
|