feat(api): 开发auth、login等接口,规范格式化
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { ApiError } from './api-error.js';
|
||||
import { AppLogger } from '../logging/app-logger.js';
|
||||
|
||||
@Catch()
|
||||
export class ApiErrorFilter implements ExceptionFilter {
|
||||
public constructor(private readonly logger: AppLogger) {}
|
||||
|
||||
public catch(exception: unknown, host: ArgumentsHost) {
|
||||
const response = host.switchToHttp().getResponse<{
|
||||
status: (status: number) => {
|
||||
json: (body: unknown) => unknown;
|
||||
};
|
||||
}>();
|
||||
const request = host.switchToHttp().getRequest<{
|
||||
requestId?: string;
|
||||
method?: string;
|
||||
originalUrl?: string;
|
||||
}>();
|
||||
const requestId = request.requestId ?? `req_${randomUUID()}`;
|
||||
if (exception instanceof ApiError) {
|
||||
const body = exception.getResponse() as {
|
||||
error: Record<string, unknown>;
|
||||
};
|
||||
return response
|
||||
.status(exception.getStatus())
|
||||
.json({ error: { ...body.error, request_id: requestId } });
|
||||
}
|
||||
if (exception instanceof HttpException) {
|
||||
return response.status(exception.getStatus()).json({
|
||||
error: {
|
||||
code: 'HTTP_ERROR',
|
||||
message: '请求无法处理',
|
||||
request_id: requestId,
|
||||
},
|
||||
});
|
||||
}
|
||||
this.logger.error(
|
||||
'unhandled_exception',
|
||||
exception instanceof Error ? exception.stack : undefined,
|
||||
{
|
||||
request_id: requestId,
|
||||
method: request.method,
|
||||
path: request.originalUrl,
|
||||
},
|
||||
);
|
||||
return response.status(500).json({
|
||||
error: {
|
||||
code: 'INTERNAL_ERROR',
|
||||
message: '服务器暂时无法处理请求',
|
||||
request_id: requestId,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { HttpException, HttpStatus } from '@nestjs/common';
|
||||
|
||||
export class ApiError extends HttpException {
|
||||
public constructor(
|
||||
status: HttpStatus,
|
||||
code: string,
|
||||
message: string,
|
||||
details?: unknown[],
|
||||
) {
|
||||
super({ error: { code, message, details } }, status);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user