Nest HttpExceptionFilter

发布时间 2023-05-26 10:27:36作者: develon

UseFilters

UseFilters 作用于控制器:

import { Controller, UseFilters } from '@nestjs/common';

@Controller('user')
@UseFilters(MyHttpExceptionFilter)
export class UserController {
  ...
}

如果需要全局过滤器:

import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { ConfigService } from '@nestjs/config';
import { AppModule } from './app.module';
import { text } from 'body-parser';
import * as xmlparser from 'express-xml-bodyparser';
import * as cookieParser from 'cookie-parser';
import { join } from 'path';
import { GlobalExceptionFilter } from './common/filter/global.filter';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  app.enableCors();
  app.use(cookieParser());
  app.use(text());
  app.use(xmlparser());
  app.useStaticAssets(join(process.cwd(), 'public'));
  app.useGlobalFilters(new GlobalExceptionFilter());
  const configService = app.get(ConfigService);
  process.title = configService.get<string>('TITLE');

  const PORT = configService.get<number>('PORT');
  await app.listen(PORT);

  console.log(`server running at port:${PORT}`);
}
bootstrap();