优化表单验证错误处理
This commit is contained in:
@@ -1,11 +1,25 @@
|
|||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
import { ValidationPipe } from '@nestjs/common';
|
import { BadRequestException, ValidationPipe } from '@nestjs/common';
|
||||||
import { ResponseInterceptor } from './common/interceptors/response.interceptor';
|
import { ResponseInterceptor } from './common/interceptors/response.interceptor';
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
const app = await NestFactory.create(AppModule);
|
const app = await NestFactory.create(AppModule);
|
||||||
app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));
|
app.useGlobalPipes(new ValidationPipe({
|
||||||
|
transform: true,
|
||||||
|
whitelist: true,
|
||||||
|
stopAtFirstError: true,
|
||||||
|
exceptionFactory: (errors) => {
|
||||||
|
const error = errors[0];
|
||||||
|
const firstConstraint = error.constraints ? Object.values(error.constraints)[0] : '验证失败';
|
||||||
|
|
||||||
|
throw new BadRequestException({
|
||||||
|
message: firstConstraint,
|
||||||
|
error: 'Bad Request',
|
||||||
|
statusCode: 400
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}));
|
||||||
app.useGlobalInterceptors(new ResponseInterceptor());
|
app.useGlobalInterceptors(new ResponseInterceptor());
|
||||||
await app.listen(process.env.PORT ?? 3001);
|
await app.listen(process.env.PORT ?? 3001);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user