【问题标题】:How to make custom response in pipe of nestjs如何在nestjs的管道中进行自定义响应
【发布时间】:2021-04-09 09:12:19
【问题描述】:

我在nestjs中制作了如下的HttpExceptionFilter。

import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';
import { Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception, host: ArgumentsHost) {
    const context = host.switchToHttp();
    const response = context.getResponse<Response>();
    const status = (exception.getStatus && exception.getStatus()) || 500;

    response.status(status).json({
      code: status,
      success: false,
    });
  }
}

然后我把它放到 app.module 中全局使用。

@Module({
  imports: [
  ],
  controllers: [AppController],
  providers: [
    AppService,
    {
      provide: APP_FILTER,
      useClass: HttpExceptionFilter,
    },
  ],
})

到目前为止,除了nestjs的管道外,它都运行良好。 我制作了一个管道,并在其他控制器中使用 @UsePipes 制作了它。

这是我的管道代码。

import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';

@Injectable()
export class SplitEmailPipe implements PipeTransform<string, string> {
  transform(value: any, metadata: ArgumentMetadata): any {
    let email = '';
    try {
      email = value.split('@')[1];
    } catch (err) {
      throw new Error(err);
    }
    return { email };
  }
}

我使用@UsePipes 放置了那个管道。
在这种情况下,管道效果很好。

  @Post('/')
  @UsePipes(new SplitEmailPipe())
  public async signIn(
    @Res() res,
    @Body() signInDto: SignInDto,
  ) {
    ... do something
  }

但问题是 HttpExceptionFilter 不起作用。它默认响应nestjs。
你能给我一些关于这个问题的建议吗?

【问题讨论】:

    标签: javascript node.js typescript nestjs


    【解决方案1】:

    发生这种情况是因为您没有从 HttpException 类型中引发错误,要解决此问题,您应该替换:

      import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';
    
    @Injectable()
    export class SplitEmailPipe implements PipeTransform<string, string> {
      transform(value: any, metadata: ArgumentMetadata): any {
        let email = '';
        try {
          email = value.split('@')[1];
        } catch (err) {
          throw new BadRequestException(err);
        }
        return { email };
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-08
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 2022-08-07
      • 2019-10-30
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      相关资源
      最近更新 更多