docs: 完善项目说明和注释
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
// 统一的业务错误类型。
|
||||
// service 层抛出 HttpError,app.ts 的全局错误处理器负责转换成 HTTP 响应。
|
||||
export class HttpError extends Error {
|
||||
constructor(
|
||||
public readonly statusCode: number,
|
||||
public readonly code: string,
|
||||
message: string,
|
||||
public readonly details?: unknown,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "HttpError";
|
||||
}
|
||||
}
|
||||
|
||||
// 下面这些工厂函数让业务代码只表达语义,不需要到处手写状态码和错误码。
|
||||
export function badRequest(message: string, details?: unknown): HttpError {
|
||||
return new HttpError(400, "BAD_REQUEST", message, details);
|
||||
}
|
||||
|
||||
export function notFound(message: string): HttpError {
|
||||
return new HttpError(404, "NOT_FOUND", message);
|
||||
}
|
||||
|
||||
export function conflict(message: string): HttpError {
|
||||
return new HttpError(409, "CONFLICT", message);
|
||||
}
|
||||
|
||||
export function internalServerError(message: string): HttpError {
|
||||
return new HttpError(500, "INTERNAL_SERVER_ERROR", message);
|
||||
}
|
||||
|
||||
export function unauthorized(message: string): HttpError {
|
||||
return new HttpError(401, "UNAUTHORIZED", message);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// 统一成功响应结构,便于前端稳定读取 success/data 字段。
|
||||
export function ok<T>(data: T) {
|
||||
return {
|
||||
success: true,
|
||||
data,
|
||||
};
|
||||
}
|
||||
|
||||
// 201 Created 通常用于 POST 请求,表示资源创建成功,并返回新资源的详细信息。
|
||||
export function created<T>(data: T) {
|
||||
return {
|
||||
success: true,
|
||||
data,
|
||||
};
|
||||
}
|
||||
|
||||
// 列表接口统一返回 items + pagination,避免每个 controller 自己拼分页结构。
|
||||
export function paginated<T>(
|
||||
items: T[],
|
||||
page: number,
|
||||
pageSize: number,
|
||||
total: number,
|
||||
) {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
items,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
totalPages: Math.ceil(total / pageSize),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user